为什么这个哨兵控制回路不能工作?
我应该可以输入尽可能多的名字,当我输入一个-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;
}

最佳答案

你的程序有很多问题。我懒得向他们解释并提出解决办法。
我重写了你的代码:

#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动态分配内存。

10-05 21:52