How Can I avoid char input for an int variable?

Viewed 42517

The program below shows a 'int' value being entered and being output at the same time. However, when I entered a character, it goes into an infinite loop displaying the previous 'int' value entered. How can I avoid a character being entered?

#include<iostream>
using namespace std;

int main(){
int n;

while(n!=0){
            cin>>n;
            cout<<n<<endl;
           }
return 0;
}
4 Answers
#include <iostream>
#include <climits> // for INT_MAX limits
using namespace std;
int main()
{
    int num;
    cout << "Enter a number.\n";
    cin >> num;
    // input validation
    while (cin.fail())
    {
        cin.clear(); // clear input buffer to restore cin to a usable state
        cin.ignore(INT_MAX, '\n'); // ignore last input
        cout << "You can only enter numbers.\n";
        cout << "Enter a number.\n";
        cin >> num;
    }
}

You need to check for cin fail

And

You need clear the input stream

See the following example. It is tested in recent compilers

#include <iostream>
using namespace std;

void ignoreLine()
{
    cin.clear();
    cin.ignore();
}

int main(int argc, char const* argv[])
{
    int num;
    cout << "please enter a integer" << endl;
    cin >> num;

    while (cin.fail()) {
        ignoreLine();
        cout << "please enter a integer" << endl;
        cin >> num;
    }

    cout << "entered num is - " << num << endl;

    return 0;
}
Related