xto*_*ofl 5 c++ parsing istream
如何检测istream提取是否失败?
string s("x");
stringstream ss(s);
int i;
ss >> std::ios::hex >> i;
Run Code Online (Sandbox Code Playgroud)
编辑 - 虽然问题标题涵盖了这一点,但我忘了提到身体:我真的想要检测失败是由于错误的格式化,即解析,还是由于任何其他与IO相关的问题,以便提供正确的反馈(malformed_exception("x")或其他).
if(! (ss >> std::ios::hex >> i) )
{
std::cerr << "stream extraction failed!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
就这么简单.
ETA:以下是此测试如何与流的结尾进行交互的示例.
int i;
std::stringstream sstr("1 2 3 4");
while(sstr >> i)
{
std::cout << i << std::endl;
if(sstr.eof())
{
std::cout << "eof" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
将打印
1
2
3
4
eof
如果您要检查sstr.eof()或sstr.good()处于while循环状态,则不会打印4.
首先:感谢您提供有用的答案。然而,经过一些调查(cfr.cppreference )和验证后,似乎检查解析失败的一种方法是检查标志ios::failbit,如
const bool parsing_failed = (ss >> ios::hex >> i).rdstate() & ios::failbit ;
Run Code Online (Sandbox Code Playgroud)
虽然建议istream::operator!和istream::operator bool混合failbit 在一起 badbit(参见 cplusplusreference 上的此处和那里)。