Let me show you my source at first.
#include <iostream>
#include <limits>
using namespace std;
int main() {
int n;
while (true) {
cout << "Type >> ";
cin >> n;
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Not a number" << endl;
continue;
}
if (n % 2)
cout << "odd";
else
cout << "even";
cout << endl;
}
return 0;
}
Well, This code can run without any problems. however, if I swap between cin.clear() and cin.ignore(), then type character(not integer), it stucks in infinite loop. (consult next code)
#include <iostream>
#include <limits>
using namespace std;
int main() {
int n;
while (true) {
cout << "Type >> ";
cin >> n;
if (cin.fail()) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
cout << "Not a number" << endl;
continue;
}
if (n % 2)
cout << "odd";
else
cout << "even";
cout << endl;
}
return 0;
}
I wonder sequence is neccesary between cin.clear() and cin.ignore(). if it is, I wanna know why it needs sequence.
Thx for read my Question. I will be very appreciated for any your replies. sorry for inarticulate Writing.