我正在用 C 创建一个程序,我必须接受一个整数才能继续。我阅读了一些问题以使用以下代码,但我的程序在输入任何字符后很快就进入无限循环。请帮助我
int tnum,scancheck;
printf("Enter the number of teams(Maximum 4)\n");
scancheck = scanf("%d",&tnum);
while(scancheck != 1)
{
printf("ERROR: Please enter numbers only\n\n");
printf("Enter the number of teams(Maximum 4)\n");
scancheck = scanf("%d",&tnum);
}
我使用了基里连科的方法,但我的程序在输入特殊字符(例如l=)时进入无限循环
编辑 问题已解决。谢谢大家
最佳答案
您必须在调用 scanf
之间清理 stdin
。否则,具有无效输入的 scanf
的行为是将字符放回流中。然后,它进入无限循环,每次迭代都会读取相同的错误字符。
#include <stdio.h>
void clean_stdin(void) {
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
}
/* ... */
int ret;
int n;
do {
ret = scanf("%d", &n);
clean_stdin();
} while (ret != 1);
关于c - 在 C 中验证整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12978647/