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).
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);
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With