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

Is there a simple way to get the number of characters printed in C++?

printf(...) returns 输出到控制台的字符数,我觉得这对设计某些程序很有帮助。所以,我想知道 C++ 中是否有类似的功能,因为 cout<< 是一个没有 return 类型的运算符(至少从我的理解来看是这样)。

您可以将自己的streambuf关联到cout来统计字数。

这是 class 包罗万象:

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.

打印的字符

您可以创建一个过滤流缓冲区来报告写入的字符数。例如:

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);
}