有没有一种简单的方法来获得用C++打印的字符数?

Del*_*lla 9 c++ printf iostream cout console-application

printf(...)返回输出到控制台的字符数,我发现在设计某些程序时非常有帮助.所以,我想知道C++中是否有类似的功能,因为cout <<是一个没有返回类型的运算符(至少根据我的理解).

Wer*_*nze 6

您可以关联自己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;
};
Run Code Online (Sandbox Code Playgroud)

你这样使用它:

{
    CCountChars c(cout);
    cout << "bla" << 3 << endl;
}
Run Code Online (Sandbox Code Playgroud)

当对象实例存在时,它会计算cout输出的所有字符.

请记住,这只会计算字符输出cout,而不是打印的字符printf.