2016-12-29 67 views
8

printf(...)返回輸出到控制檯的字符數,我發現這對設計某些程序非常有幫助。所以,我想知道在C++中是否有類似的功能,因爲cout <是一個沒有返回類型的運算符(至少從我瞭解的情況來看)。有沒有一種簡單的方法來獲取用C++打印的字符數?

+2

我認爲最好的方法是輸出到內存緩衝區(用'ostringstream'),指望它,然後將該緩衝區輸出到控制檯 –

+2

我總是發現複雜的格式可以讓老式C函數更輕鬆。是否有任何特定的原因要避免printf? –

+0

哎呀,對不起。我甚至不知道printf是用C++編寫的,認爲它必須是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輸出的字符數,而不是使用printf打印的字符數。

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); 
} 
相關問題