-1

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;
    }
noobiee
  • 27
  • 1
  • 10

1 Answers1

1

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;
        }
nullptr
  • 511
  • 1
  • 5
  • 16
  • sorry for the late reply. thank you for your explanation it was very clear. what i did is cin.ignore(1000,'\n'); and im not sure if this is good code for this. i tried your code and it works fine. thanks again – noobiee Apr 17 '18 at 14:40