有没有一种简单的方法来获取用C ++打印的字符数? [英] Is there a simple way to get the number of characters printed in C++?
问题描述
printf(...)
返回输出到控制台的字符数,这对设计某些程序很有帮助。因此,我想知道C ++中是否存在类似功能,因为cout<<是没有返回类型的运算符(至少从我的理解)。
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).
推荐答案
您可以将自己的 streambuf
关联到 cout
来计算字符。
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;
};
您可以这样使用:
{
CCountChars c(cout);
cout << "bla" << 3 << endl;
}
当对象实例存在时,它将计算cout输出的所有字符。
While the object instance exists it counts all characters output by cout.
请记住,这只会计算通过 cout
输出的字符,而不是通过 printf打印的字符
。
Keep in mind that this will only count characters output via cout
, not characters printed with printf
.
这篇关于有没有一种简单的方法来获取用C ++打印的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!