0
我想獲得用戶輸入使用fgets和一些時髦(不正確)的事情正在發生,我似乎無法理解爲什麼。fgets裏面的For循環造成奇怪的行爲
程序運行的參數指示用戶輸入的值有多少。
這裏是程序應該如何運行:
./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
謝謝克里斯,解決了它!它總是小事。 – FrankyJ542