哨兵控制的循环不起作用

时间:2015-07-11 07:35:21

标签: c sentinel

为什么这个哨兵控制回路不起作用?

我应该能够输入尽可能多的名字,当我输入-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;
}

2 个答案:

答案 0 :(得分:2)

您的计划存在很多问题。我懒得解释它们并建议修复它们。

我重写了你的代码:

#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 :(得分:0)

至少1 st 致电

puts(namedata);

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