2013-10-15 4 views
4

ostream 개체에 쿼리를 작성했는지 여부를 쿼리 할 수 ​​있습니까? ostringstream의 경우 사용할 수 있습니다.주어진 ostream 개체가 작성되었는지 확인하십시오.

if(!myOssObject.str().empty()) 

일반적인 경우는 어떻습니까? ofstream 또는 cout 또는 cerr? 일반적 호에서

+0

stream.rdbuf() -> [in_avail()] (http://en.cppreference.com/w/cpp/io/basic_streambuf/in_avail)과 같은 것이 있습니까? –

+1

@TomKnapen'std :: streambuf :: in_avail'은 출력의 영향을받지 않아야합니다. –

답변

5

당신은 tellp()에 의해 (버퍼링 데이터를 전송) 세척하기 전에 작성된 것입니다 얼마나 많은 문자 (또는 뭔가 다른) 찾을 수 있습니다

:

는의 출력 위치 인디케이터 (indicator)를 돌려줍니다 현재 연결된 streambuf 개체입니다.

cout << "123"; 

if (cout.tellp() > 0) 
{ 
    // There is some data written 
} 

세척 한 후,이 출력 스트림 그들이 작성한 것을하지만 마지막 상태 플래그를 잊지 것입니다.

출력 장치가 실시간이며 아무 것도 버퍼링하지 않으면 tellp은 도움이되지 않습니다.

3

사전에 스트림 에 손을들 수있는 경우에만 가능합니다. 유일한 일반적으로 보장 솔루션 문자 출력의 수를 추적 유지하는 필터링 streambuf의, 삽입하는 것입니다 평소처럼

class CountOutput : public std::streambuf 
{ 
    std::streambuf* myDest; 
    std::ostream* myOwner; 
    int myCharCount; // But a larger type might be necessary 

protected: 
    virtual int overflow(int ch) 
    { 
     ++ myCharCount; 
     return myDest->sputc(ch); 
    } 

public: 
    CountOutput(std::streambuf* dest) 
     : myDest(dest) 
     , myOwner(NULL) 
     , myCharCount(0) 
    { 
    } 
    CountOutput(std::ostream& dest) 
     : myDest(dest.rdbuf()) 
     , myOwner(&dest) 
     , myCharCount(0) 
    { 
     myOwner->rdbuf(this); 
    } 
    ~CountOutput() 
    { 
     if (myOwner != NULL) { 
      myOwner.rdbuf(myDest); 
     } 
    } 

    int count() const 
    { 
     return myCount; 
    } 
}; 

을이 함께 사용할 수있는 단지 std::ostream 어떤 약 :

CountOutput counter(someOStream); 
// output counted here... 
int outputCount = counter.count(); 

범위를 벗어나면 스트림 원래 상태 으로 복원됩니다.

+3

Boost.Iostreams에는 학습 시간을 할애하고 싶다면 [카운터 클래스] (http://www.boost.org/doc/libs/1_54_0/libs/iostreams/doc/index.html)가 있습니다. 정확하게 그; 줄과 문자를 세어서 전달합니다. – DanielKO

+0

나는 그 중 하나를 인식하지 못했지만 일반적으로 내 필터링 streambuf 기술을 지원한다는 것을 알고 있습니다. –

관련 문제