简体   繁体   English

ostringstream的字符串构造函数的目的是什么?

[英]What is the purpose of ostringstream's string constructor?

On MSVC 2005, I have the following code. 在MSVC 2005上,我有以下代码。

std::ostringstream stream("initial string ");
stream << 5;
std::cout << stream.str();

What I expect is: 我的期望是:

initial string 5

What I get is: 我得到的是:

5nitial string

Initializing the stream with a string, I would expect the stream to move its position to the end of the initial string. 使用字符串初始化流,我希望流将其位置移动到初始字符串的末尾。 Obviously, STL doesn't agree with me (not the first time). 显然,STL不同意我的观点(不是第一次)。

What's the purpose of such behavior? 这种行为的目的是什么? Is this use case useful for anything? 这个用例对任何事情都有用吗? Also, is there a way to advance the stream position to the end of the initial string? 还有,有办法将流位置推进到初始字符串的末尾吗?

Using an ostringstream and providing an initial value is just like opening an existing file for writing. 使用ostringstream并提供初始值就像打开现有文件进行编写一样。 You have some data there, and unless you specify otherwise, your initial position will be at the beginning of the data. 您有一些数据,除非另有说明,否则您的初始位置将位于数据的开头。 You can seek in the data, or you specify ios::ate to initially position the write pointer to the end of the existing data, or you can specify ios::app to always position the write pointer to the end of the existing data. 您可以在数据中查找,或者指定ios::ate以将写指针初始定位到现有数据的末尾,或者您可以指定ios::app始终将写指针定位到现有数据的末尾。

您可以指定构造函数的第二个(可选)参数,以在末尾设置流游标:

std::ostringstream stream("initial string ", std::ios::ate);

To seek to the end, do this: 为了寻求最终,请执行以下操作:

stream.seekp(0, ios_base::end);

As to why the write position defaults to the front, I don't know. 至于为什么写位置默认为前面,我不知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM