gpt4 book ai didi

c++ - 初始化 stringstream.str( a_value ) 和 stringstream << a_value 之间的区别

转载 作者:IT老高 更新时间:2023-10-28 23:19:53 26 4
gpt4 key购买 nike

考虑:

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); 有什么区别?和字符串流 << a_value;并且,具体来说,为什么第一个不允许通过 << 进行连接,但第二个允许?

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

最佳答案

您遇到的问题是因为 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以后的新模式)

更多详情可查看here .

如果您想要 附加 行为,请创建您的 stringstreamios_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?

关于c++ - 初始化 stringstream.str( a_value ) 和 stringstream << a_value 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13558306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com