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

我的未来我决定 提交于 2020-01-03 08:37:12

问题


printf(...) returns the number of characters output to the console, which I find very helpful in designing certain programs. So, I was wondering if there is a similar feature in C++, since the cout<< is an operator without a return type (at least from what I understand of it).


回答1:


You can associate your own streambuf to cout to count the characters.

This is the class that wraps it all:

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

And you use it like this:

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

While the object instance exists it counts all characters output by cout.

Keep in mind that this will only count characters output via cout, not characters printed with printf.




回答2:


You could create a filtering stream buffer which reports the number of characters written. For example:

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

You'd just use this stream buffer as a filter:

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


来源:https://stackoverflow.com/questions/41377045/is-there-a-simple-way-to-get-the-number-of-characters-printed-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!