在下面的示例中,如果我在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;
}
答案 0 :(得分: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;
}