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

时间:2012-11-26 03:28:49

标签: c++ initialization concatenation stringstream

考虑:

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 is over-written by s_b 
// 
// Replacing line *** above with "ss_2 << ss_2.str() << " " << s_b;"
//                    results in ss_2 having the same content as ss_1.

问题:

  1. stringstream.str(a_value)之间的区别是什么?和 stringstream&lt;&lt;一个值;而且,具体来说,为什么第一个没有 允许通过&lt;&lt;连接但第二个呢?

  2. 为什么ss_1会自动在s_a和fen之间获得空白,但是 我们是否需要在可能的行中明确添加空格 替换行***:ss_2 << ss_2.str() << " " << s_b;

2 个答案:

答案 0 :(得分:4)

建议您阅读stringstream参考:http://en.cppreference.com/w/cpp/io/basic_stringstream

std::stringstream::str()替换基础字符串的内容

operator<<将数据插入流中。

答案 1 :(得分:4)

您遇到的问题是因为std::stringstream默认使用ios_base::openmode mode = ios_base::in|ios_base::out构建,这是非追加模式。

您对此处的输出模式感兴趣(即:ios_base::openmode mode = ios_base::out

std::basic_stringbuf::str(const std::basic_string<CharT, Traits, Allocator>& s)以两种不同的方式运作,具体取决于openmode

  1. mode & ios_base::ate == false :(即:非附加输出流):

    str会设置pptr() == pbase(),以便后续输出覆盖从s复制的字符

  2. mode & ios_base::ate == true :(即:追加输出流):

    str会设置pptr() == pbase() + s.size(),以便后续输出追加到从s复制的最后一个字符

  3. (请注意,追加模式是自c ++ 11以来的新功能)

    可以找到更多详细信息here

    如果您想要附加行为,请使用stringstream创建ios_base::ate

    std::stringstream ss(std::ios_base::out | std::ios_base::ate)
    

    这里的简单示例应用程序:

    #include <iostream>
    #include <sstream>
    
    void non_appending()
    {
        std::stringstream ss;
        std::string s = "hello world";
    
        ss.str(s);
        std::cout << ss.str() << std::endl;
    
        ss << "how are you?";
        std::cout << ss.str() << std::endl;
    }
    
    void appending()
    {
        std::stringstream ss(std::ios_base::out | std::ios_base::ate);
        std::string s = "hello world";
    
        ss.str(s);
        std::cout << ss.str() << std::endl;
    
        ss << "how are you?";
        std::cout << ss.str() << std::endl;
    }
    
    int main()
    {
        non_appending();
        appending();
    
        exit(0);
    }
    

    这将以上述两种不同的方式输出:

    hello world
    how are you?
    hello world
    hello worldhow are you?