非数字输入导致无限循环
出于某种原因,如果用户输入了错误的数据类型,例如’j’或’%’,循环将停止询问输入,并将一遍又一遍地显示"Enter an integer >"
。 如何让程序处理错误输入? 为什么输入非数值会导致这种奇怪的行为呢?
#define SENTINEL 0; int main(void) { int sum = 0; /* The sum of numbers already read */ int current; /* The number just read */ do { printf("\nEnter an integer > "); scanf("%d", ¤t); if (current > SENTINEL) sum = sum + current; } while (current > SENTINEL); printf("\nThe sum is %d\n", sum); }
如果scanf()
无法找到匹配的输入,则current
变量将保持不变:检查scanf()
返回值:
/* scanf() returns the number of assignments made. In this case, that should be 1. */ if (1 != scanf("%d", ¤t)) break;
如果您希望在输入无效后继续接受输入,则需要从stdin
读取无效数据,因为它将保留,如注释中的pmg所指出的那样。 一种可能的方法是使用格式说明符"%*s"
来读取输入但不执行任务:
if (1 != scanf("%d", ¤t)) { scanf("%*s"); } else { }
一种方法是将输入读入字符串,然后将字符串转换为所需的数据类型。
我的C有点生疏,但我记得使用fgets()
读取字符串,然后sscanf()
将字符串解析/“读取”到我感兴趣的变量中。