Redirected to cout & # 8594; std :: stringstream, does not see EOL

I read a bunch of messages about redirecting std :: cout to string streams, but I have a 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 select new lines in the initial release - can someone enlighten me on how to do this?

Thanks.

+3
source share
2 answers

Works great for me:
Note: std :: getline () reads a line (but not the "\ n" character, the line terminator is discarded after reading each line). But the loop will be entered once for each row.

#include <iostream>
#include <sstream>

int main()
{
    std::stringstream   redirectStream;
    std::streambuf*     oldbuf  = std::cout.rdbuf( redirectStream.rdbuf() );

    std::cout << "Hello1\n";
    std::cout << "Hello2\n";

    std::string str;
    while(std::getline(redirectStream, str))
    {
        fprintf(stdout,"Line: %s\n",str.c_str());
        // loop enter once for each line.
        // Note: str does not include the '\n' character.
    }

    // In real life use RAII to do this. Simplified here for code clarity.
    std::cout.rdbuf(oldbuf);
}

. , - std:: cout. , streamirectstreamstream , , std:: cout, -. std:: cout , "redirectStream", , std:: cout . , .

+3

. , . , , , ! , :

// Basically... 
std::string str; 
std::stringstream redirectstream; 
// perform the redirection... 
// ... 

while (!done)
{ 
  while(std::getline(redirectStream, str)) 
  { 
    // stuff... 
  } 
  std::cout << "Hello1\n"; 
  std::cout << "Hello2\n"; 
} 

, getline() . ?

, , .

0

Source: https://habr.com/ru/post/1725289/


All Articles