printf(...)
返回输出到控制台的字符数,我发现这对于设计某些程序非常有帮助。所以,我想知道 C++ 中是否有类似的功能,因为 cout
您可以关联自己的streambuf
to cout
来计算字符数。
这是包装所有内容的类:
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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)