在下面的示例中,如果我在 Mac OS X 终端中输入一个字符,程序将陷入无限循环,打印 Please enter a number:
一行一行,并且不允许用户输入任何内容。这段代码有什么问题?解决方法是什么?
我想更改代码,如果未输入数字,则会提示用户错误消息并要求重新输入数字。
#include <stdio.h>
int main(int argc, const char * argv[]) {
int number = 0, isnumber;
getagin: printf("Please enter a number:\n");
isnumber = scanf("%i", &number);
if(isnumber) {
printf("You enterd a number and it was %i\n", number);
} else {
printf("You did not eneter a number.\n");
goto getagin;
}
return 0;
}
编辑:我在阅读建议后编辑了代码,并修复了无限循环问题。对于无限循环问题来说,这并不是一个糟糕的解决方案,通过一个简单的 for 循环,我告诉 C 搜索任何非数字字符。下面的代码不允许像 123abc
这样的输入.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, const char * argv[]) {
char line[10];
int loop, arrayLength, number, nan;
arrayLength = sizeof(line) / sizeof(char);
do {
nan = 0;
printf("Please enter a number:\n");
fgets(line, arrayLength, stdin);
for(loop = 0; loop < arrayLength; loop++) { // search for any none numeric charcter inisde the line array
if(line[loop] == '\n') { // stop the search if there is a carrage return
break;
}
if((line[0] == '-' || line[0] == '+') && loop == 0) {
continue;
} // Exculude the sign charcters infront of numbers so the program can accept both negative and positive numbers
if(!isdigit(line[loop])) { // if there is a none numeric character then add one to nan and break the loop
nan++;
break;
}
}
} while(nan || strlen(line) == 1); // check if there is any NaN or the user has just hit enter
sscanf(line, "%d", &number);
printf("You enterd number %d\n", number);
return 0;
}
最佳答案
输入非数字时出现无限循环的原因是缓冲区中留下的非数字字符,因为 scanf
不会在下次读取 时读取该字符。 scanf
(因为它与格式说明符不匹配)。在下一次迭代中 scanf
再次找到该字符,但不读取它并立即退出。这种情况会反复发生,并且您将陷入无限循环。放置一个 while(getchar() != '\n');
语句来使用该字符。
试试这个
#include <stdio.h>
int main(int argc, const char * argv[]) {
int number = 0, isnumber;
getagin: printf("Please enter a number:\n");
isnumber = scanf("%i", &number);
if(isnumber) {
printf("You enterd a number and it was %i\n", number);
} else {
printf("You did not eneter a number.\n");
while(getchar() != '\n'); // T consume all non-digits
goto getagin;
}
return 0;
}
关于c - 为什么这个例子在C中陷入了无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829672/