[英]Using scanf() inside a while loop but the loop does not terminate
我正在用C编写一个程序,希望用户仅在输入两个整数时才运行循环。 我在用
while(scanf(" %d %d" ,&a ,&b) == 2)
但是,如果我输入更多或更少的输入,程序不会终止。 如果我输入一个输入,程序将等待下一行的第二个输入。 如果我输入了三个输入,则程序将使用前两个整数,而第三个将等待后续输入。
我认为使用getchar()
可能会有所帮助,但我不知道如何。
我究竟做错了什么?
我应该如何终止程序?
我应该如何终止程序?
那就是应该如何表现的。
为了获得预期的输出,您可以使用类似
int a, b;
char c;
for(;;) /* Infinite loop */
{
if(scanf("%d%c%d", &a, &c, &b) == 3 && c == ' ' && getchar() == '\n')
break; /* Break out of the loop */
fputs("Invalid input; Try again", stderr);
if(c != '\n')
while((c = getchar()) != '\n' && c != EOF); /* Clear the `stdin` */
}
scanf返回在stdin中读取的字符数。 它可以正常工作。 如果输入单个整数,则scanf将等待第二个整数参数。 您输入的是两个以上的整数,但是您的scanf只读取前两个整数。 因此,它返回两个,并且循环不会终止。 如果要正确检查此问题,请使用以下示例进行检查。
例:-
#include<stdio.h>
int main()
{
int x;
int y;
int i;
while((scanf("%d %d",&x, &y) == 2) && (i = getchar()) == '\n')
{
/* do your operations what you want */
}
}
我希望这能帮到您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.