简体   繁体   中英

I am using stringstream with my own buffer, but its str() method doesn't related to my buffer?

I want to use my own buffer zone for the stringstream, but changing the buffer twice won't expect two output just as the code shown follow.

std::stringstream ss;
char buffer[10];
memset(buffer, '\0', sizeof buffer);

ss.rdbuf()->pubsetbuf(buffer, sizeof buffer);
sprintf(buffer, "abcd");
std::cout << ss.str() << std::flush;

ss.rdbuf()->pubsetbuf(buffer, sizeof buffer);
sprintf(buffer, "efgh");
std::cout << ss.str() << std::flush;

And the result is:

abcd

After I setting the buffer to "efgh", the ss.str() doesn't show me the new content, why is that?

And the reason why I want to directly set the internal buffer is that it should be a system call like recv.

Now I found out that event if I change the buffer totally using pubsetbuf in the second calling, it does not change at all, remaining the previous contents.

ss is a different object than the "buffer" it is not a pointer to "buffer". When you do "pubsetbuf" you copy the contents of buffer into "ss". You might want to try using "ss<<buffer" instead anyway, it will be easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM