簡體   English   中英

初始化stringstream.str(a_value)和stringstream << a_value之間的差異

[英]Difference between initializations stringstream.str( a_value ) and 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 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 << a_value; 而且,具體來說,為什么第一個不允許通過<<但第二個進行連接?

  2. 為什么ss_1會自動在s_a和save之間獲得空白,但是我們是否需要在行中明確添加可以替換行***的 ss_2 << ss_2.str() << " " << s_b;ss_2 << ss_2.str() << " " << s_b;

建議你閱讀stringstream參考: http//en.cppreference.com/w/cpp/io/basic_stringstream

std::stringstream::str()替換基礎字符串的內容

operator<<數據插入流中。

您遇到的問題是因為默認情況下使用ios_base::openmode mode = ios_base::in|ios_base::out構造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復制的最后一個字符

(注意,這個追加模式是新的,因為c ++ 11)

更多細節可以在這里找到。

如果您想要追加行為,請使用ios_base::ate創建stringstream

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?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM