Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I avoid char input for an int variable?

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;
}
like image 923
Scoop Avatar asked Jul 17 '12 13:07

Scoop


1 Answers

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;
}
like image 112
SHAH MD IMRAN HOSSAIN Avatar answered Sep 30 '22 13:09

SHAH MD IMRAN HOSSAIN