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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With