摘自Stroustrup的TC ++ PL,第三版,第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: 123After: 0state: failbit
谢谢。
相关分类