Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of ostringstream's string constructor?

On MSVC 2005, I have the following code.

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).

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?

like image 877
Jesse Stimpson Avatar asked Oct 01 '10 15:10

Jesse Stimpson


People also ask

What is ostringstream in c++?

std::ostringstreamOutput stream class to operate on strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str .

How do I reset Ostringstream?

str(""); s. clear(); The first line is required to reset the string to be empty; the second line is required to clear any error flags that may be set. If you know that no error flags are set or you don't care about resetting them, then you don't need to call clear() .


2 Answers

Using an ostringstream and providing an initial value is just like opening an existing file for writing. 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.

like image 195
Jerry Coffin Avatar answered Oct 20 '22 22:10

Jerry Coffin


You can specify the second (optional) parameter of the constructor to set the stream cursor at the end:

std::ostringstream stream("initial string ", std::ios::ate);
like image 23
Khaled Alshaya Avatar answered Oct 20 '22 21:10

Khaled Alshaya