[英]What is the behavior of the C++ method ostream::exceptions(iostate state) supposed to be?
[英]C++ iostream iostate
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
using namespace std;
int main()
{
int ival;
while(cin >> ival, !cin.eof())
{
if(cin.bad())
throw runtime_error("IO stream corrupted");
if(cin.fail())
{
cerr<< "bad data,try again"<<endl;
cin.clear(istream::failbit);
continue;
}
}
}
我的英语很差,并为此道歉。 编译完这段代码并运行后,我在控制台中输入和“a”,并且它处于死循环中,我不能在其中输入另一个字母表? 谁能告诉我发生了什么?
问题是std::basic_ios::clear
实际上并没有清除你提供的位。 它设置您提供的位。
这里有两个问题:
如http://en.cppreference.com/w/cpp/io/basic_ios/clear std::basic_ios::clear
中所述, 它不会清除您提供的位, 而是设置它 。 因此,您需要设置好goodbit
。
您需要刷新流以防止换行损坏您的循环
这应该以预期的方式工作
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <limits>
using namespace std;
int main()
{
int ival;
while(cin >> ival, !cin.eof())
{
cout<< cin.rdstate()<<endl;
if(cin.bad())
throw runtime_error("IO stream corrupted");
if(cin.fail())
{
cout<< "bad data,try again"<<endl;
cin.clear(istream::goodbit); // Set the goodbit
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.