I am trying to check the input value, and I run this program below. But when I give a wrong input it goes into infinite loop. I tried the cin.clear();
but still it goes to infinite loop. Please can anyone give me a solution for this.
#include<iostream>
using namespace std;
int main()
{
int c=0;
cout<<"in test"<<endl;
//cin.clear();
cin>>c;
if(cin.fail())
{
cout<<"please try again"<<endl;
main();
}
else
cout<<"c = "<<c<<endl;
return 0;
}
Use cin.ignore()
after cin.clear()
to remove the invalid input from stream buffer. Using cin.clear()
does not remove the previous input, so it keeps going into an infinite loop. cin.clear()
only resets the state, i.e., the error flags etc.
Try this:
cin.ignore(INT_MAX,'\n');
It clears till the first newline is encountered.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다