2013-08-15 3 views
13
나는 아래의 코드 조각을 시도했지만이 원하는 출력 제공되지

:차이 이제 stringstream 및 ostringstream

#include<iostream> 
#include<sstream> 
using namespace std; 
void MyPrint(ostream& stream) 
{ 
    cout<<stream.rdbuf()<< endl; 
} 
int main() 
{ 
    stringstream ss; 
    ss<<"hello there"; 
    MyPrint(ss);    //Prints fine 

    ostringstream oss; 
    oss<<"hello there"; 
    MyPrint(oss);    //Does not print anything 
    getchar(); 
} 

내가 stringstreamostringstream 사이에 유일하게 가능한 차이가 있음을 알고를 그 후에 힘 방향과 stringstream보다 약간 빠릅니다.

나는 무엇을 놓치고 있습니까?

추신 : 비슷한 질문이 이전에 게시되었지만 답변을 얻지 못했습니다.

답변

21

std::stringstreamstd::ostringstream은 플래그를 std::stringbuf으로 전달합니다. 특히 std::stringbuf (std::ostringstream)은 독서를 지원하지 않습니다. 그리고 std::cout << stream.rdbuf()은 streambuf에서 읽기 작업 입니다.

std::ostringstream에서 문자를 추출하는 방법은 std::ostringstream::str() 기능을 사용하여 입니다.

0

stringstream은 ostringstream 및 istringstream의 양방향 구현으로 생각해서는 안됩니다. 스트림 스트림과 스트림 스트림의 구현 클래스로 구현되어 입력 및 출력 기능을 모두 구현합니다.

어느 것을 사용할지 선택하는 것은 사용되는 용도에 따라 다릅니다. 스트림을 통해 데이터에 액세스 할 수없는 상태에서 스트림에 데이터를 쓰면되는 경우에는 스트림 만 있으면됩니다. 그러나 API에 제공하는 항목에 양방향을 구현하고 제한하고 싶다면 다음과 같이 캐스팅 할 수 있습니다.

stringstream ss; // My bidirectional stream 

ostringstream *p_os = &ss; // Now an output stream to be passed to something only allowed to write to it. 

int bytes = collectSomeData(p_oss); 
관련 문제