我的程序出了什么问题?当我第一次输入数字时,它会在 if 中打印语句,但是当我退出程序并使用 char 重新输入时,它会在 else 中打印语句,并且当我继续输入数字时循环永远不会退出。
#include <stdio.h>
#include <ctype.h>
int main()
{
int x;
char y;
for(x=0;x<4;x++)
{
puts("Please enter a number:");
scanf("%c",&y);
if(isdigit(y))
{
printf("Y is a digit!\n");
break;
}
else
{
printf("Y is not a number, please enter another number:\n");
scanf("%d",&y);
}
}
return 0;
}
最佳答案
我认为您的程序中有一个错误,特别是在 else
部分。您使用了 scanf("%d",&y);
而不是 scanf("%c",&y);
。
%d
用于整数,但 y
的声明是 char,因此必须使用 %c
。
关于c - isdigit 和 scanf 具有无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392326/