来自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"; …Run Code Online (Sandbox Code Playgroud) 考虑:
std::string s_a, s_b;
std::stringstream ss_1, ss_2;
// at this stage:
// ss_1 and ss_2 have been used and are now in some strange state
// s_a and s_b contain non-white space words
ss_1.str( std::string() );
ss_1.clear();
ss_1 << s_a;
ss_1 << s_b;
// ss_1.str().c_str() is now the concatenation of s_a and s_b,
// <strike>with</strike> without space between them
ss_2.str( s_a );
ss_2.clear();
// ss_2.str().c_str() is now s_a
ss_2 << s_b; // line ***
// ss_2.str().c_str() the value of s_a …Run Code Online (Sandbox Code Playgroud)