2016-12-29 5 views
8

printf(...)은 콘솔에 출력되는 문자 수를 반환합니다. 이는 특정 프로그램을 설계 할 때 매우 유용합니다. C++에서 이와 유사한 기능이 있는지 궁금합니다. < <은 반환 유형이없는 연산자입니다 (적어도 내가 이해하고있는 것부터).C++로 인쇄 된 문자 수를 얻는 간단한 방법이 있습니까?

+2

내가 (ostringstream''으로) 가장 좋은 건 메모리 버퍼로 출력하는 것입니다 생각, 그 버퍼를 콘솔에 출력합니다. –

+2

예전 학교 C 함수를 사용하면 더 복잡한 형식을 쉽게 찾을 수있었습니다. printf를 피하고자하는 특별한 이유가 있습니까? –

+0

죄송합니다. 나는 C++에서 printf가 작동한다는 것을 알지 못했지만, cout <<이되어야한다고 생각했다. – Della

답변

5

streambufcout에 연결하여 문자 수를 계산할 수 있습니다.

이 모든 것을 감싸는 클래스 :

class CCountChars { 
public: 
    CCountChars(ostream &s1) : m_s1(s1), m_buf(s1.rdbuf()), m_s1OrigBuf(s1.rdbuf(&m_buf)) {} 
    ~CCountChars() { m_s1.rdbuf(m_s1OrigBuf); m_s1 << endl << "output " << m_buf.GetCount() << " chars" << endl; } 

private: 
    CCountChars &operator =(CCountChars &rhs) = delete; 

    class CCountCharsBuf : public streambuf { 
    public: 
     CCountCharsBuf(streambuf* sb1) : m_sb1(sb1) {} 
     size_t GetCount() const { return m_count; } 

    protected: 
     virtual int_type overflow(int_type c) { 
      if (streambuf::traits_type::eq_int_type(c, streambuf::traits_type::eof())) 
       return c; 
      else { 
       ++m_count; 
       return m_sb1->sputc((streambuf::char_type)c); 
      } 
     } 
     virtual int sync() { 
      return m_sb1->pubsync(); 
     } 

     streambuf *m_sb1; 
     size_t m_count = 0; 
    }; 

    ostream &m_s1; 
    CCountCharsBuf m_buf; 
    streambuf * const m_s1OrigBuf; 
}; 

는 그리고 당신은 다음과 같이 사용 : 객체 인스턴스가 존재

{ 
    CCountChars c(cout); 
    cout << "bla" << 3 << endl; 
} 

동안은 cout을 모든 문자의 출력을 계산합니다.

이것은 으로 인쇄 된 문자가 아닌 cout을 통해 출력 된 문자 수만 포함한다는 점에 유의하십시오.

1

작성된 문자 수를보고하는 필터링 스트림 버퍼를 만들 수 있습니다. 예를 들어 :

class countbuf 
    : std::streambuf { 
    std::streambuf* sbuf; 
    std::streamsize size; 
public: 
    countbuf(std::streambuf* sbuf): sbuf(sbuf), size() {} 
    int overflow(int c) { 
     if (traits_type::eof() != c) { 
      ++this->size; 
     } 
     return this->sbuf.sputc(c); 
    } 
    int sync() { return this->sbuf->pubsync(); } 
    std::streamsize count() { this->size; } 
}; 

당신은 단지 필터로이 스트림 버퍼를 사용하십시오 : 그것을 계산,

int main() { 
    countbuf sbuf; 
    std::streambuf* orig = std::cout.rdbuf(&sbuf); 
    std::cout << "hello: "; 
    std::cout << sbuf.count() << "\n"; 
    std::cout.rdbuf(orig); 
}