2015-07-11 89 views
0

为什么这个定点控制回路不工作?定点控制回路不起作用

我应该能够输入尽可能多的名字,因为我想输入一个-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; 
} 
+1

'scanf(“%s”,&names);'是错误的。 'names'是一个'int'。 –

+2

有时使用'names'变量作为数字,有时用作字符,有时用作字符串。 – dlask

+1

我可以直接指向你的调试器吗? –

回答

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动态分配内存。为namedata使用未初始化

+0

酷派感谢!问题如何将-1添加到数组 – mar

+0

-1是*不*添加到数组'nameData'。这是因为输入被扫描到'temp'中。然后一个条件检查它是否是“-1”。如果是这样,跳出循环。如果没有,它会打印输入,将其添加到数组中,并增加'count'。 –

0

至少1 ST调用

puts(namedata); 

引发未定义的行为,事后什么事情都有可能发生。

+1

在此之前,'scanf(“%s”,&names);'是UB。 –

+0

@CoolGuy:正确,这就是为什么我措辞“*至少*”... ;-) – alk