KnowledgeSeeker
KnowledgeSeeker

Reputation: 57

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?

Upvotes: 1

Views: 87

Answers (1)

mch
mch

Reputation: 9804

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

Upvotes: 2

Related Questions