Stringstream Doesn’t Include Initial Data

My problem is really petty, but nevertheless I have not found any answer by asking google or by asking peers. The problem can be shown by the following code:

std::ostringstream oss("I am a ");
    oss << "donkey";
    std::cout << oss.str();

Expected Output: “I am a donkey”

Actual Output: “donkey”

What happens here? Is the initial string the stringstream had to begin with been discarded?

Answer

You have to add std::ios_base::ate to the constructor, otherwise it would overwrite from the beginning:

#include <iostream>
#include <sstream>
using namespace std;
 
int main() {
    std::ostringstream oss("I am a ", std::ios_base::ate);
    oss << "donkey";
    std::cout << oss.str();
    return 0;
}

https://ideone.com/IIfOkB

More information: https://en.cppreference.com/w/cpp/io/basic_ostringstream

Example: https://en.cppreference.com/w/cpp/io/basic_ostringstream/str

Leave a Reply

Your email address will not be published. Required fields are marked *