【发布时间】:2014-01-16 18:08:55
【问题描述】:
在下面的示例中,如果我在 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;
}
【问题讨论】:
-
goto在这里没有任何问题 - 如果他使用 while 循环也会发生同样的情况。 -
那么如何更改代码,如果没有输入数字,则提示用户错误消息并要求再次输入数字?
-
goto 与为什么他没有看到问题有关,imo...
-
@Bandrami 阅读了 Vaughn 评论中的讨论——同样的问题没有
goto关键字。 -
@Bandrami 他不知道当缓冲区的内容与格式字符串不匹配时
scanf是如何工作的。使用循环不会解决这个问题。
标签: c infinite-loop goto