why std::cin in step 3 is omitted?
I don't understand, why cin >> W;
in step 3 is omitted, if i input not a number (i.e. 's').
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
short W = -1;
cout << "step 1) W = " << W << endl;
cout << "give a number: ";
cin >> W;
if ( cin.fail() )
{
cout << "ERROR, bad number" << endl;
W = -1;
cout << endl << "step 2) W == " << W << endl;
cin.clear();
}
cout << endl <<开发者_高级运维 "step 3) W == " << W << endl;
cout << "give a number: ";
cin >> W;
cout << endl << "step 4) W == " << W << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
I'm assuming, you are puzzled by the case where you enter a non-number for step 1 and then the step 3 seems not to work.
The problem is, that cin.clear() clears only the error flags of the stream. The wrong input is not taken out of the stream, so the next cin >> W
just reads the same wrong input again.
You can for example fill a string from cin which takes everything or you can use cin.ignore()
to ignore the following characters in the input stream.
See http://www.arachnoid.com/cpptutor/student1.html for a more detailed explanation.
精彩评论