看來我的fgets()的實現在這裏是不正確的,非常感謝一些額外的眼睛來看看我所做的!fgets在C中導致無限循環
下面的代碼
int main(int argc, const char* argv[]){
int numIntegers;
char buffer[20];
int intArray[10];
//if no argument is passed in, terminate
if (argc == 1){
printf("no argument given, terminating..\n");
return EXIT_FAILURE;
}
else{
numIntegers = atoi(argv[1]);
//we only want numbers greater than 0
if (numIntegers <= 0){
printf("# must be greater than 0\n");
return EXIT_FAILURE;
}
else{
printf("Enter %d integer values to place in array: \n", numIntegers);
for (int i = 0; i < numIntegers; i++){
fgets(buffer, numIntegers, stdin);
intArray[i] = atoi(buffer);
printf("Index is = %d \n", i);
}
}
}
//for (int i =0; i < numIntegers; i++){
// printf("Index[%d] = %d \n", i, intArray[i]);
//}
}
這裏的輸出,與除的整數沒有其它文本行是用戶輸入。注意我的價值是如何重置的。只有當我給出超過10的任何初始參數時纔會出現此問題。無論出於何種原因,它都會將for循環變成無限循環。
$ ./a.out 11
Enter 11 integer values to place in array:
5
Index is = 0
2
Index is = 1
1
Index is = 2
2
Index is = 3
3
Index is = 4
4
Index is = 5
123
Index is = 6
123
Index is = 7
123
Index is = 8
1
Index is = 9
2
Index is = 2
2
Index is = 3
3
Index is = 4
5
Index is = 5
1
Index is = 6
12
Index is = 7
這是一個相當本地化的問題,但解釋發生了什麼(超出標準的「檢查你的界限」建議)是一種很酷的方式。請務必閱讀我的答案的結尾。 – Floris