【问题标题】:Can I Set an ostream Delimiter我可以设置一个 ostream 分隔符吗
【发布时间】:2014-07-02 11:25:08
【问题描述】:

我想对流中的大量输入进行空间分隔。
我知道我可以使用std::ostream_iterator 的分隔符构造函数,但并不是我所有的输入都是相同的类型。

有没有一种方法可以让流默认使用分隔符?

std::ostringstream foo;
foo << 1 << 1.2 << "bar" // I want this to print "1 1.2 bar "

【问题讨论】:

    标签: c++ delimiter ostream


    【解决方案1】:

    你可以像下面这样包装流,(只是一个基本的想法

    struct mystream 
    {
         mystream (std::ostream& os) : os(os) {}
         std::ostream&   os;
    };
    
    template <class T> 
    mystream& operator<< (mystream& con, const T& x) 
    { 
         con.os << x << " "; // add extra delimeter
         return con; 
    }
    
    
    int main() 
    {
        std::ostringstream foo;
        mystream c(foo) ; // mystream c( std::cout ) ;
    
        c << 1 << 1.2 << "bar" ;
    }
    

    here

    【讨论】:

    • c &lt;&lt; std::setw(10) &lt;&lt; std::setprecision(3) &lt;&lt; std::hexfloat &lt;&lt; 3.14159;
    【解决方案2】:

    您可以使用流缓冲区和虚拟函数将此功能捆绑到流中。例如:

    class space_delimited_output_buffer : public std::streambuf
    {
    public:
        space_delimited_output_buffer(std::streambuf* sbuf)
            : m_sbuf(sbuf)
        { }
    
        virtual int_type overflow(int_type c)
        {
            return m_sbuf->sputc(c);
        }
    
        virtual int sync()
        {
            if (ok_to_write)
                this->sputc(' ');
            else
                ok_to_write = true;
    
            return internal_sync();
        }
    private:
        std::streambuf* m_sbuf;
        bool ok_to_write = false;
    
        int internal_sync()
        {
            return m_sbuf->pubsync();
        }
    };
    
    class space_delimited_output_stream
        : public std::ostream
        , private virtual space_delimited_output_buffer
    {
    public:
        space_delimited_output_stream(std::ostream& os)
            : std::ostream(this)
            , space_delimited_output_buffer(os.rdbuf())
        {
            this->tie(this); 
        }
    };
    
    int main() {
        space_delimited_output_stream os(std::cout);
        os << "abc" << 123 << "xyz";
    }
    

    Live demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多