问题
I'm trying to learn C++ from an older edition of the Primer, and tried to execute some of their code relating to iostream objects, which gave me some trouble:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
int ival;
try
{
while (cin >> ival, !cin.eof())
{
if (cin.bad())
throw runtime_error("IO stream corrupted");
if (cin.fail())
{
cerr << "Invalid input - try again";
cin.clear(iostream::failbit);
continue;
}
else
cout << ival << endl;
}
return EXIT_SUCCESS;
}
catch(runtime_error err)
{
cout << err.what();
return EXIT_FAILURE;
}
}
When this program encounters an invalid input, it outputs "Invalid input - try again" without stopping, signaling that cin.clear(iostream::failbit)
doesn't actually "clear" cin's failbit. I also tried just using cin.clear()
to no avail. So my question is, how do I return cin to a non-error state?
回答1:
If I'm not mistaken, cin.clear(iostream::failbit) sets the new state to fail. You should first get rid of that part of the input that is causing the problems and then use cin.clear()
or cin.clear(iostream::goodbit)
.
For more information, look here: http://www.cplusplus.com/reference/ios/ios/clear/
来源:https://stackoverflow.com/questions/17012270/how-to-clear-the-state-bits-in-an-iostream-object-in-c