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.