[英]Setting the content of a std::stringstream with str(const char*) has strange consequences
我广泛使用std::stringstream
来生成代码。 当使用str()
函数设置内容,然后使用operator<<
时,我遇到了一些奇怪的行为。 有人可以向我解释这种行为。 我非常感谢 - 谢谢。
示例一:
std::stringstream ssa;
ssa.str("Setting string");
std::cout << ssa.str() << std::endl;
ssa << " adding to string";
std::cout << ssa.str() << std::endl;
输出:
设置字符串
添加到字符串
预期:
设置字符串
设置字符串添加到字符串
所以在对文档进行一些阅读之后,我发现我应该将开放模式设置为ios_base::ate
:
std::stringstream ssb(std::ios_base::ate);
ssb.str("Setting string");
std::cout << ssb.str() << std::endl;
ssb << " adding to string";
std::cout << ssb.str() << std::endl;
输出:
设置字符串
设置字符串
再次(或现在)我期望:
设置字符串
设置字符串添加到字符串
为什么我会得到我的结果,我如何得到我想要的结果? Ei能够设置string
的初始string
stringstream
加到该string
吗?
我知道我可以将内容设置为空string("")
,然后只使用<<operator
。 这实际上是我正在使用的解决方法。 我只是不明白观察到的行为。 解决方法使我的代码更加混乱。
std::stringstream
对象的默认打开模式是in | out
in | out
使用其他模式会覆盖这些选项。 由于无法写入流,因此插入操作符不能用于写入流。 这就是为什么str()
给出相同的输出两次。
您还需要在输出模式下手动打开流:
std::stringstream ssb("Setting string", std::ios_base::out | std::ios_base::ate);
或者,使用std::ostringstream
,它使用out | mode
来初始化内部std::stringbuf
子对象 out | mode
。
std::ostringstream("Setting string", std::ios_base::ate);
你忘了设置标志模式: std::ios_base::out
。 这将有效:
std::stringstream ssb(std::ios_base::out | std::ios_base::ate);
ssb.str("Setting string");
std::cout << ssb.str() << std::endl;
ssb << " adding to string";
std::cout << ssb.str() << std::endl;
输出:
Setting string
Setting string adding to string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.