1

I want the user to enter only two integers, and no more than two. The user should enter two integers separated by spaces. So, for example:

  1. The valid input is: 1 2
  2. Invalid input: 1 2 3
#include<stdio.h>  
     int main(){
       int a;
       int b;
       printf("Enter input:\n");
       int numbers = scanf("%d %d", &a, &b);
       if(numbers != 2){
            printf("Invalid input.\n");
            }
    else{   printf("First: %d Second: %d\n", a, b);
     }  return 0;
    }

If I enter more than 2 integers, the program accepts the first 2 integers and ignores the third. In this case, I want to print an error, but the program still ends. So my question is, what should I do to achieve my needs?

thanks.

hhhhh
  • 13
  • 3

1 Answers1

2

Your problem is that scanf is doing what it's supposed to. The user has entered three numbers, but scanf has only consumed two of them. If you used scanf to read another number, it would consume that third one.

You should probably be using fgets to consume an entire line of input, then using sscanf to read out the two numbers, then if it finds the two, you can check for more to validate your input.

Chris
  • 26,361
  • 5
  • 21
  • 42