我正在尝试创建一个程序,要求输入一些内容并检查它是否为整数。如果它是一个整数,则打印“整数是...”。否则,打印“再试一次”并等待另一个输入。但是,如果您输入一个字符,该程序会打印无限次的“再试一次”。这是源代码:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int inp;
bool t = 1;
printf("type an integer\n");
while (t) {
if (scanf("%i", &inp) == 1) {
printf("The integer is %i", inp);
t = 0;
} else {
printf("try again");
scanf("%i", &inp);
}
}
}
最佳答案
OP 的代码无法使用有问题的非数字输入。它保留在 stdin
中,用于下一个输入函数。不幸的是,它只是另一个以同样方式失败的 scanf("%i", &inp)
- 无限循环。
尝试读取 int
后,读取该行的其余部分。
#include <stdio.h>
#include <stdbool.h>
int main() {
int inp;
int scan_count;
printf("Type an integer\n");
do {
scan_count = scanf("%i", &inp); // 1, 0, or EOF
// consume rest of line
int ch;
while ((ch == fgetchar()) != '\n' && ch != EOF) {
;
}
} while (scan_count == 0);
if (scan_count == 1) {
printf("The integer is %i\n", inp);
} else {
puts("End of file or error");
}
}
更好的方法是使用 fgets()
读取用户输入行。 Example
关于检查输入程序陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292347/