问题
istream &func(istream &in)
{
string data;
while (in >> data, !in.eof()) {
if (in.bad())
throw runtime_error("IO stream corrupted");
if (in.fail()) {
cerr << "bad data, try again" << endl;
in.clear();
in.ignore(200);
continue;
}
cout << data << endl;;
}
//in.clear(istream::eofbit | istream::failbit);
in.clear();
return in;
}
why in.clear(istream::eofbit | istream::failbit);
can not reset the cin?
but in.clear
can make it.
PS: I use this function in main(), and use cin
as its parameter.
回答1:
clear is defined like this:
void clear(iostate state = goodbit);
So, effectively, in.clear();
is doing this: in.clear(istream::goodbit);
which resets the stream. Calling in.clear(istream::eofbit | istream::failbit);
would set both the eofbit
and failbit
, I doubt that is what you want.
std::cin.clear(std::istream::eofbit | std::istream::failbit);
std::ios_base::iostate state = std::cin.rdstate();
if( state == (std::istream::eofbit | std::istream::failbit))
{
std::cout << "eofbit and failbit set" << std::endl;
}
来源:https://stackoverflow.com/questions/10877275/iostream-clear