【问题标题】:sentinel controlled loop does not work哨兵控制回路不起作用
【发布时间】:2015-07-11 15:57:39
【问题描述】:

为什么这个哨兵控制循环不起作用?

我应该能够输入任意数量的名称,当我输入-1 时,它应该会终止。

有人能指出正确的方向吗?

#include <stdio.h>
#include <string.h>

int main()
{
  char namedata[50];

  int n, count = 0, names = 1;

  while (names > 0)
  {
    printf("Enter family member name:\n");
    scanf("%s", &names);
    printf("name:");
    puts(namedata);

    if (names > 0)
    {
      namedata[count] = names;
      count = count + 1;
    }
  }

  if (strcmp(names, "crystal") == 0)
  {
    printf("crsytal is cool");
  }

  return 0;
}

【问题讨论】:

  • scanf("%s", &amp;names); 是错误的。 namesint
  • 您将names 变量用作数字,有时用作字符,有时用作字符串。
  • 我可以指导您使用调试器吗?

标签: c sentinel


【解决方案1】:

您的程序有很多问题。我懒得解释它们并为它们提出修复建议。

我已经重写了你的代码:

#include <stdio.h>
#include <string.h>

int main(){
    char namedata[100][50]; /* 2D array of 100x50 bytes size
                               It can hold upto a max of 100 strings
                               each of max 50 bytes */

    char temp[50]; /* temp array to scan input */

    int count = 0, i;

    while (count < 100) /* Loop until there is no more space to store input */
    {

        printf("Enter family member name:\n");
        scanf("%49s", temp); /* Scan in the input (maximum of 49 chars, +1 for '\0') */

        if (strcmp(temp, "-1") == 0) /* If user typed -1 */
        {
            break; /* Break out of the loop */
        }

        /* Otherwise */

        printf("name:");
        puts(temp);        /* Print the input */

        /* Copy input into the last of the location of the array */
        strcpy(nameData[count], temp); 

        /* Increment count */
        count++;  
    }

    for(i = 0; i < count; i++) /* Loop in each index of the array where names are stored */
    {
        if (strcmp(namedata[i], "crystal") == 0) /* If a match is found */
        {
            printf("crsytal is cool");
        }
    }

    return 0;   
}

如果你不想在char namedata[100][50];这里有固定大小,你需要通过malloc/calloc/realloc动态分配内存。

【讨论】:

  • 帅哥谢谢!!提问 -1 怎么会被添加到数组中
  • -1 添加到数组nameData。这是因为输入被扫描到temp。然后一个条件检查它是否是"-1"。如果是这样,请跳出循环。如果不是,它会打印输入,将其添加到数组中,然后递增 count
【解决方案2】:

至少 1st 调用

puts(namedata);

在未初始化使用namedata 时引发未定义的行为,之后任何事情都可能发生。

【讨论】:

  • 在此之前,scanf("%s", &amp;names); 是 UB。
  • @CoolGuy:正确,这就是我用“至少”措辞的原因... ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-11
  • 1970-01-01
相关资源
最近更新 更多