Pergunta

I want to output the content of a ostringstream to some other stream (for example std::cout). I know that I can use std::ostringstream::str() but I assume it has an overhead on copying the stream contents to a string and then further to the other stream. I found that I could use std::ostringstream::rdbuf() (Comment suggesting that has 25 votes). But it breaks std::cout as is shown in the output of the test program below. Am I doing something wrong?

#include <iostream>
#include <sstream>

int main(int argc, char const *argv[])
{
    std::ostringstream ss;
    ss << "some data" << std::endl;
    std::cerr << std::cout << std::endl;
    std::cout << "start" << std::endl;
    std::cout << ss.str();
    std::cout << ss.rdbuf();
    std::cout << "end" << std::endl;
    std::cerr << std::cout  << std::endl;
    return 0;
}

Results in:

0x6013b8
start
some data
0
Foi útil?

Solução

Your problem is that the rdbuf() buffer for an ostringstream is, as you might expect from the name, write only (the ostringstream returns the string through the str() method). You can't read the data back out of it through the buffer pointer.

Change your ostringstream to stringstream and it should work fine.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top