Recover from C++ istream failure sample
The code is not coded in a standard way where it would altogether avoid the problem but does exhibit the recover from C++ istream failure which occur in a while loop.
void main_menu(){
int condition = 1;
int input = 0;
do {
cout << "please input an integer\n";
if(cin.fail()) {
//if it encounter a fail state which is error type. it will ignore the buffer
//associate with istream
cin.ignore(100);
cin.clear();
//reset the fail state to be good
}
cin >> input;
fflush(stdin); //fflush alone not suffice for some reason thou it works on scanf
if (input == 1) {
cout << "Hello World\n";
condition=0;
system("Pause");
} else { condition=1; }
}
while (condition == 1 );
}
void main_menu(){
int condition = 1;
int input = 0;
do {
cout << "please input an integer\n";
if(cin.fail()) {
//if it encounter a fail state which is error type. it will ignore the buffer
//associate with istream
cin.ignore(100);
cin.clear();
//reset the fail state to be good
}
cin >> input;
fflush(stdin); //fflush alone not suffice for some reason thou it works on scanf
if (input == 1) {
cout << "Hello World\n";
condition=0;
system("Pause");
} else { condition=1; }
}
while (condition == 1 );
}
Comments