For循环中的fgets导致奇怪的行为

时间:2013-10-16 00:19:49

标签: c fgets

我正在尝试使用fgets获取用户输入,并且正在发生一些时髦(不正确)的事情,我似乎无法理解为什么。

程序使用一个参数运行,该参数指示用户输入的值的数量。

以下是程序的运行方式:

./a.out 6
Enter 6 integer values to place in tree:
5
4
3
2
1
6
Input values:
5
4  
3
2
1
6

如果我有1作为参数,它甚至不允许我输入输入,0来自哪里?

./a.out 1
Enter 1 integer values to place in tree:
Input values:
0

如果我有2作为参数,它只允许我输入1个输入并且幻像0再次出现。

./a.out 2
Enter 2 integer values to place in tree:
1
Input values: 
1
0

如果我有3个或更多参数,它可以正常运行。

这是来源:

int main (int argc, const char* argv[]){
   int numIntegers;
   char buffer[20];
   if (argc == 1){
      printf("Usage: a.out #\n");
      return EXIT_FAILURE;
   }
   else{
      numIntegers = atoi(argv[1]);
      if (numIntegers <= 0){
         printf("# must be greater than 0\n");
         return EXIT_FAILURE; 
      }
      else{
         int intArray[numIntegers];
         printf("Enter %d integer values to place in tree: \n", numIntegers);
         for (int i = 0; i < numIntegers; i++){
            fgets(buffer, numIntegers, stdin);
            intArray[i] = atoi(buffer);
         }
         printf("Input values:\n");
         for (int i = 0; i < numIntegers; i++){
            printf(%d\n", intArray[i]);
         }
      }
   }
}//end main

1 个答案:

答案 0 :(得分:0)

fgets() size 参数指的是buffer的大小,在您的情况下应为20。

fgets(buffer, sizeof(buffer), stdin);

顺便说一句,你的代码实际上不会编译。

printf(%d\n", intArray[i]);    // missing a quotation mark
相关问题