Tuesday, 12 June 2012

Appending string to STL stringstream

std::stringstream constructor has two optional parameters: string that this stream will be initialized with and the buffer mode. Default mode for stringstream is ios::in|ios::out. Put pointer (the one that points to the location in the buffer where the next output operation will start inserting characters) is always set to location 0 upon stream creation regardless of the buffer content. That explains why Test 2 in the code below yields overwriting of the content on the second output.

If we want to initialize stream during its creation and to make next output operation to append characters, we need to move put pointer to the end of the buffer explicitly - by setting buffer open mode to ios::ate (see Test 3).

main.cpp:


Output:
Test 1:
Contained string: "abc"; Output pointer position: 3
Contained string: "abcdef"; Output pointer position: 6

Test 2:
Contained string: "abc"; Output pointer position: 0
Contained string: "def"; Output pointer position: 3

Test 3:
Contained string: "abc"; Output pointer position: 3
Contained string: "abcdef"; Output pointer position: 6