#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf(" %d", &i) > 0) // step-2
printf("Num=%d\n", i);
else
printf("Entered character.Pls enter int\n");
}
}
当我使用字符输入运行上述代码时,如果用户输入了整数以外的值,我想再次继续扫描,它正在运行无限循环。请提出原因或任何解决方案...?
最佳答案
#include <stdio.h>
int main() {
int i;
while (1) {
printf("Enter no?\n"); // step -1
if (scanf_s(" %d", &i) > 0) { // step-2
printf("Num=%d\n", i);
break;
}
else {
printf("Entered character.Pls enter int\n");
fseek(stdin, 0, SEEK_END);
}
}
}
关于c - C中的无限while循环不等待再次扫描数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068025/