简体   繁体   English

在while循环中使用scanf()但循环不会终止

[英]Using scanf() inside a while loop but the loop does not terminate

I am writing a program in C in which i want the loop to run only if the user enters two integers . 我正在用C编写一个程序,希望用户仅在输入两个整数时才运行循环。 I am using 我在用

while(scanf(" %d %d" ,&a ,&b) == 2)

But the program does not terminate if i enter more or less inputs. 但是,如果我输入更多或更少的输入,程序不会终止。 If i enter a single input, the program waits for the second input on next line . 如果我输入一个输入,程序将等待下一行的第二个输入。 If i enter three inputs, the program takes first two integers and the third one waits for subsequent input. 如果我输入了三个输入,则程序将使用前两个整数,而第三个将等待后续输入。

I think using getchar() might help but i don't know how. 我认为使用getchar()可能会有所帮助,但我不知道如何。

What am i doing wrong? 我究竟做错了什么?

How should i terminate the program? 我应该如何终止程序?

How should i terminate the program? 我应该如何终止程序?

  1. You can terminate it by entering invalid input, such as a letter. 您可以通过输入无效的输入(例如字母)来终止它。
  2. You can terminate it by entering a key combination that means EOF on the console - Ctrl+D if you are using Linux. 您可以通过在控制台上输入表示EOF的组合键来终止它-如果您使用的是Linux,请按Ctrl + D。

That is how it is supposed to behave. 那就是应该如何表现的。

To get the expected output you can use something like 为了获得预期的输出,您可以使用类似

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` */
}

The scanf returns how many characters read in stdin. scanf返回在stdin中读取的字符数。 It works correctly. 它可以正常工作。 If you enter a single integer then the scanf will wait for the second integer argument. 如果输入单个整数,则scanf将等待第二个整数参数。 You are entering more than two integers but your scanf reads only the first two integers. 您输入的是两个以上的整数,但是您的scanf只读取前两个整数。 So, it returns two and your loop will not be terminate. 因此,它返回两个,并且循环不会终止。 If you want to check this correctly using the below example to check. 如果要正确检查此问题,请使用以下示例进行检查。

Example:- 例:-

#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 */
        }
}

I hope this will help you. 我希望这能帮到您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM