[英]fgets inside of a For loop causing strange behavior
我正在尝试使用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
fgets()
的size参数引用buffer
的大小,在您的情况下应为20。
fgets(buffer, sizeof(buffer), stdin);
顺便说一下,您的代码实际上不会编译。
printf(%d\n", intArray[i]); // missing a quotation mark
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.