2016-12-29 60 views
8

printf(...)返回输出到控制台的字符数,我发现这对设计某些程序非常有帮助。所以,我想知道在C++中是否有类似的功能,因为cout <是一个没有返回类型的运算符(至少从我了解的情况来看)。有没有一种简单的方法来获取用C++打印的字符数?

+2

我认为最好的方法是输出到内存缓冲区(用'ostringstream'),指望它,然后将该缓冲区输出到控制台 –

+2

我总是发现复杂的格式可以让老式C函数更轻松。是否有任何特定的原因要避免printf? –

+0

哎呀,对不起。我甚至不知道printf是用C++编写的,认为它必须是cout <<。 – Della

回答

5

您可以将自己的streambufcout联系起来对字符进行计数。

这是用于包装所有的类:

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打印的字符数。

1

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

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); 
} 
相关问题