简体   繁体   English

While循环+ fgets错误

[英]While-loop + fgets error

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
int main ()
{
    char ans[100];
    int count;
    count=0;
    char *arr[100];
    char *srtarr[100];

    while(count<100)
    {
        if(strcmp(ans,"done\n")!=0)  
        {      
            printf("Enter names when done type done:");
            fgets(ans,100,stdin);       
            arr[count]=strdup(ans);
        }
        printf("%s",arr[count]);
        count++;
     }

    system("pause");
    return 0;   
}

When I run this code the program stops working. 当我运行此代码时,程序停止工作。 Im very new to c and might have made a few errors. 我对c很陌生,可能犯了一些错误。 I think the problem is either the while loop or the fgets() function. 我认为问题是while循环或fgets()函数。

EDIT: I corrected the while loop however I'm not understanding how to initialize the array. 编辑:我更正了while循环,但是我不了解如何初始化数组。 Doesn't each element within the array get filled as the loop progresses? 循环进行时,数组中的每个元素都不会被填充吗?

You initialize 'count' to 0, hit the while loop and use 'count - 1' as an array index. 您将“ count”初始化为0,打while循环,然后将“ count-1”用作数组索引。 An array index of -1 definitely could crash your program. -1的数组索引肯定会导致程序崩溃。

You have at least two cases of undefined behavior in your code: 您的代码中至少有两种未定义行为的情况:

  1. You don't in initialize any of the arrays, meaning the pointers in them are indeterminate. 您无需初始化任何数组,这意味着它们中的指针是不确定的。
  2. You use a negative index in the first iteration. 您在第一次迭代中使用负索引。

Also, you should not forget that fgets leave the newline in the string, so your string comparison will never succeed. 另外,您不要忘记fgets将换行符留在字符串中,因此字符串比较将永远不会成功。


My recommended solution: A loop while count is less than 100 , then inside the loop check for "done" (or rather "done\\n" ) using ans (before duplicating it) and break out of the loop then. 我推荐的解决方案:一个循环,当count小于100 ,然后在循环中使用ans (在复制之前)检查"done" (或更确切地说是"done\\n" ),然后退出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM