如何限制在输出流上打印的字符数?

时间:2020-09-10 22:30:32

标签: c++

要调试,我想将std :: cerr上打印的字符数限制为某个值。

为了尊重原始代码,我不想简单地删除使用std :: cerr的代码行,而是使它们无效。

在C ++中有什么方法可以实现这一点吗?

我想这样使用它:

{
    int max_char = 30;
    LimitChars c(cerr, max_char);
    // my code containing a lot of write on cerr
}

1 个答案:

答案 0 :(得分:0)

是的,要限制在 std:cerr 上打印的字符数,可以使用以下行:

{
    int max_char = 30;
    LimitChars c(cerr, max_char);
    // my code containing a lot of write on cerr
}

只需添加以下类LimitChars的定义:

#include <iostream>
#include <sstream>

using namespace std;

class LimitChars {
    public:
        LimitChars(ostream &s1, int max_val) : m_s1(s1), m_buf(s1.rdbuf(), max_val), m_s1OrigBuf(s1.rdbuf(&m_buf) ) {}
        
        ~LimitChars() {
            m_s1.rdbuf(m_s1OrigBuf); 
            //m_s1 << endl << "output " << m_buf.GetCount() << " chars" << endl;
        }
        
        int GetCount(){
            return m_buf.GetCount();
        }

    
    private:
        LimitChars &operator =(LimitChars &rhs) = delete;
    
        class LimitCharsBuf : public streambuf {
            public:
                LimitCharsBuf(streambuf* sb1, int max_val) : m_sb1(sb1), m_max_val(max_val) {}
                
                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 {
                        if( m_count >= (size_t) m_max_val ){
                            // return eof when the limit is reached (see std::streambuf::overflow for more info)
                            return streambuf::traits_type::eof();
                        }else{
                            m_count++;
                            return m_sb1->sputc((streambuf::char_type)c);
                        }
                    }
                }
                
                virtual int sync() {
                    return m_sb1->pubsync();
                }
        
                streambuf *m_sb1;
                int m_max_val;
                size_t m_count = 0;
        };

        std::ostream &m_s1;
        LimitCharsBuf m_buf;
        streambuf * const m_s1OrigBuf;

};
相关问题