문제

I am trying to learn stringstream and I have the following code:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    stringstream os;
    os.str("Purohit");
    os << "Vipul" << endl;
    cout << os.str() << endl;
}

When I compile it and run it, I get the following output:

Vipul
t

Why? Shouldn't this output Purohit Vipul?

도움이 되었습니까?

해결책

This is because str method replaces the content of stringstresm, without placing the buffer pointer for the subsequent writes at the end of the stream. That is why when you output "Vipul\n" it writes over the "Purohit" string that you placed into the stream earlier:

Initial state

0 1 2 3 4 5 6
P u r o h i t
^

After the << write:

0 1 2 3 4 5  6
V i p u l \n t    

You could call seekg to set the position before appending the "Vipul" string, but an easier fix would be to use << for both writes.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top