문제

STD :: Cout를 StringStreams로 리디렉션하는 것에 관한 많은 게시물을 읽었지만 리디렉션 된 문자열을 읽는 데 문제가 있습니다.

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"
}

초기 출력 내에서 새 라인을 선택해야합니다. 누구든지 그렇게하는 방법에 대해 나를 밝힐 수 있습니까?

감사.

도움이 되었습니까?

해결책

나를 위해 잘 작동합니다 :
참고 : std :: getline ()은 선을 읽습니다 (그러나 ' n'문자는 아니지만 각 줄을 읽은 후에 라인 터미네이터가 버려집니다). 그러나 루프는 각 라인마다 한 번 입력됩니다.

#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에 다시 넣습니다. StringStream 'RedirectStream'이 범위를 벗어나면 버퍼가 파괴됩니다. STD :: Cout은 'RedirectStream'보다 오래 살기 때문에 std :: cout가 잘못된 객체에 액세스하지 않도록해야합니다. 따라서 가장 쉬운 솔루션은 오래된 버퍼를 다시 넣는 것입니다.

다른 팁

응답에 감사드립니다. 내가 무엇을 잘못했는지 볼 수 있습니다. 내 문제를 단순화하기 위해 많은 코드를 제거했기 때문에 실제로 작동 버전을 게시했습니다! 내 실제 논리가 문제인 것 같습니다.

// 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 () 함수가 더 이상 유효하지 않은 것으로 보입니다. 이것을 설명해 주시겠습니까?

나는 이것이 완전히 다른 문제라는 것을 알고 있으며, 초기 게시물이 잘못되어 오도 한 것에 대해 사과드립니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top