I’ve read a bunch of posts regarding redirecting std::cout to stringstreams, but I’m having problem reading the redirected string.
std::stringstream redirectStream;
std::cout.rdbuf( redirectStream.rdbuf() );
std::cout << "Hello1\n";
std::cout << "Hello2\n";
while(std::getline(redirectStream, str))
{
// This does not work - as the contents of redirectStream
// do not include the '\n' - I only see "Hello1Hello2"
}
I need to pick out the new lines within the initial output – can anyone enlighten me as to how to do that?
Thanks.
Works fine for me:
Note: the std::getline() reads the line (but not the ‘\n’ character, the line terminator is thrown away after each line is read). But the loop will be entered once for each line.
Note: you need to put the old stream-buffer back in std::cout. Once the stringstream ‘redirectStream’ goes out of scope its buffer will be destroyed leaving std::cout pointing at an invalid stream-buffer. Since std::cout lives longer than ‘redirectStream’ you need to make sure that std::cout does not access an invalid object. Thus the easiest solution is to put back the old buffer.