我试图创建一个要求输入内容并检查它是否为整数的程序。如果是整数,那么打印"整数是......"。否则,打印"再试一次"并等待另一个输入。但是,该程序会打印无限数量的"再次尝试"如果你输入一个字符。这是源代码:
#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);
}
}
}
答案 0 :(得分:2)
OP的代码无法使用违规的非数字输入。它保留在.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {
border: 1px solid #fad42e;
background: #fbec88 url(images/ui-bg_flat_55_fbec88_40x100.png) 50% 50% repeat-x;
color: #363636;
}
中,用于下一个输入函数。不幸的是,只有另一个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");
}
}
读取用户输入行。 Example
答案 1 :(得分:1)
当您输入char
时,inp
中的变量scanf("%d", &inp)
将获得null
,因为输入与格式字符串不匹配。你输入的字符将保留在缓冲区中,这就是你scanf
不会停止的原因。
解决此问题的最简单方法是将第二个scanf("%i", &inp);
修改为scanf("%c", &c);
(不要忘记在主函数中声明char c
。)
答案 2 :(得分:0)
在此检查while(t)
它处于无限循环中,因为您必须为t
设置条件,例如while(t == 1)或while(t&gt; 1)或(t&lt; 1)类似的东西。说(t)意味着t可以是任何东西,它会继续运行。
答案 3 :(得分:0)
没有任何东西可以打破while循环。
考虑去除布尔值,并简单地使用while(1)循环中断。您还应该使用“%d”来表示scanf / printf中的整数。并且不需要在else中进行scanf调用,因为你的程序会循环返回并再次调用scanf。
#include <stdio.h>
int main() {
int inp = 0;
printf("type an integer\n");
while (1) {
if (scanf("%d", &inp) == 1) {
printf("The integer is %d", inp);
break;
}
else {
printf("try again");
}
}
return 0;
}
我希望这会有所帮助。