我正在为Absoulute初学者的C编程重写猜测游戏代码'使用isdigit()函数验证用户是否输入了数字。
其余代码在错误检查方面有效;但是当用户输入非数字时,代码进入无限循环。
#include <stdio.h>
#include <stdlib.h>
#define NO 2
#define YES 1
main()
{
int guessGame;
guessGame = 0;
int iRandomNum = 0;
int iResponse = 0;
printf("\n\nWould you like to play \"The Guessing Game\"?\n\n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
do{
if(guessGame == YES){
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10:\n\n ");
scanf("%d", &iResponse);
if(!isdigit(iResponse)){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
if(iResponse == iRandomNum){
printf("\nYou guessed right\n");
printf("\nThe correct guess is %d!\n", iRandomNum);
printf("\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
} else {
printf("\n\nSorry, you guessed wrong\n");
printf("\nThe correct guess was %d!\n", iRandomNum);
printf("\n\nDo you wish to continue? \n");
printf("\nType '1' for Yes or '2' for No!\n\n");
scanf("%d", &guessGame);
}
}
else {
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
scanf("%d", &iResponse);
}
}
else {
printf("\nThe window will now close. Try again later!\n");
exit(0);
}
}while(guessGame != NO);
}
答案 0 :(得分:4)
由于scanf()无法读取整数,因此代码进入无限循环。您输入的字符仍保留在键盘缓冲区中。只要字符存在于缓冲区中,就不可能读取整数。 scanf()只返回每次读为0的项目数。因此,程序不会等待用户输入数据和无限循环结果。
scanf()返回成功读取的项目数。因此,您可以简单地检查scanf()的返回值,如果它的1,则scanf()正确读取整数。
check = scanf("%d", &iResponse);
if(check == 1){
printf("\nThank you\n");
printf("\nYou entered %d\n", iResponse);
并在输入错误输入时刷新缓冲区
else {
while (getchar() != '\n'); //flush the buffer
printf("\nYou did not enter a digit\n");
printf("\n\nPlease enter a number between 1 and 10:\n\n");
//scanf("%d", &iResponse);
}
这里不需要输入,而循环将继续并在开头提示输入
答案 1 :(得分:1)
尝试以字符串的形式输入输入..你也必须比较表格中的输入数字&#39; :)