wondra
wondra

Reputation: 3573

How to write at position in stringstream

I need to write char* buffer to std::stringstream at specific position, reading through API I managed to put together following code:

std::stringstream ss;
char * str = "123";
ss.seekp(0);
ss.write(str, 3);
ss.seekp(1);
ss.write(str, 3);
std::cout << ss.str(); //expecting 1123

however does not work as expected - or more precisely does not work at all (nothing is ever written to the stream), the reason seem to be .seekp().


I just managed to confirm my suspition: the .seekp() is to blame, after removing ss.seekp(0):

std::stringstream ss;
char * str = "123";
// remove this line: ss.seekp(0);
ss.write(str, 3);
ss.seekp(1);
ss.write(str, 3);
std::cout << ss.str(); //expecting 1123

it prints 1123 as expected. Strangely enough, calling ss.seekp(0) on empty stream renders it unusable. Can somebody, please, explain me why is that so(a source in c++ documentation)?

Upvotes: 1

Views: 2836

Answers (1)

alangab
alangab

Reputation: 867

The problem is the seekp parameter:

ss.seekp(0)

tells to the stream to position at 0 relative to beginning (ie absolute) but...the stream is empty, and there's no position 0. Change it with

ss.seekp(0, std::ios_base::end);

In this way it works.

Upvotes: 2

Related Questions