how to limit the display error message to one if the user input multiple characters

the sample code that i made is to accept only integer number and will display an error message that will tell user that only integer is allowed. the problem is that when the user input multiple characters the error messages will also display the same amount of user inputs. how do i limit the display error message to one if the user input multiple characters?

this is sample output im having trouble with.

Input Integer: ab
Not a Valid Input! Please Enter a Number:Not a Valid Input! Please Enter a Number:

this is the code:

#include<iostream>

    int number_checker();

    using namespace std;

    int main(){

        int num;

        cout<<"Input Integer: ";
        num=number_checker();

        cout<<"your input is : " <<num;
    }

    int number_checker() //check if input is integer
    {
        int n;
        cin>>n;
            while(cin.fail())
            {
            cin.clear();
            cin.ignore();
            cout<<"Not a Valid Input! Please Enter a Number:";
            cin>>n;
            }
        return n;
    }

1 answer

  • answered 2018-04-14 14:35 geekCoder

    Use the fflush() function to flush thestdin buffer. The way inputs and outputs work in C are through buffers. So when you enter more than one characters, all of them get stored in the buffer. And each time the loop works, it will move a character from the buffer to the variable n.

    Take an example, if you write a code to read three integers, with cout statements between every two cin statements, and enter the three integers in one line seperated by spaces, it works just fine.

    int a, b, c;
    cout << "Enter an integer: ";
    cin >> a;
    cout << "Enter an integer: ";
    cin >> b;
    cout << "Enter an integer: ";
    cin >> c;
    cout << "Enter an integer: ";
    cout << a <<" " << b << " " << c << endl;
    

    And you give the input as:

    10 20 30
    

    The program works fine, except that the output will be

    Enter an integer: 10 20 30
    Enter an integer: Enter an integer: 10 20 30
    

    You get the idea, right? When you use fflush(stdin), it clears the stdin buffer. So that there are no pending inputs.

    Modifying your while loop to this should work:

    while(cin.fail())
            {
            cin.clear();
            fflush(stdin);
            cout<<"Not a Valid Input! Please Enter a Number:";
            cin>>n;
            }