简体   繁体   中英

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 . 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.

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.

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. It works correctly. If you enter a single integer then the scanf will wait for the second integer argument. You are entering more than two integers but your scanf reads only the first two integers. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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