来自 Stroustrup 的 TC++PL,第 3 版,第 21.3.3 节:
如果我们尝试读入变量 v 并且操作失败,则 v 的值应该保持不变(如果 v 是 istream 或 ostream 成员函数处理的类型之一,则它不变)。
下面的例子似乎与上面的引用相矛盾。根据上面的引用,我期望 v 的值保持不变——但它会归零。这种明显矛盾的行为的解释是什么?
#include <iostream>
#include <sstream>
int main( )
{
std::stringstream ss;
ss << "The quick brown fox.";
int v = 123;
std::cout << "Before: " << v << "\n";
if( ss >> v )
{
std::cout << "Strange -- was successful at reading a word into an int!\n";
}
std::cout << "After: " << v << "\n";
if( ss.rdstate() & std::stringstream::eofbit ) std::cout << "state: eofbit\n";
if( ss.rdstate() & std::stringstream::failbit ) std::cout << "state: failbit\n";
if( ss.rdstate() & std::stringstream::badbit ) std::cout << "state: badbit\n";
return 1;
}
我使用 x86_64-w64-mingw32-g++.exe (rubenvb-4.7.2-release) 4.7.2 得到的输出是:
Before: 123
After: 0
state: failbit
谢谢。