小编use*_*664的帖子

为什么stringstream >>在失败时改变目标值?

来自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)

c++ state stringstream cin

53
推荐指数
1
解决办法
2598
查看次数

初始化stringstream.str(a_value)和stringstream << a_value之间的差异

考虑:

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)

c++ initialization concatenation stringstream

13
推荐指数
1
解决办法
2248
查看次数

标签 统计

c++ ×2

stringstream ×2

cin ×1

concatenation ×1

initialization ×1

state ×1