我可以设置ostream分隔符吗?

Can I Set an ostream Delimiter

本文关键字:分隔符 ostream 设置 我可以      更新时间:2023-10-16

我想用空格分隔流中的许多输入。
我知道我可以使用std::ostream_iterator的分隔符构造函数,但并非所有输入都是相同类型的。

是否有一种方法可以告诉流默认使用分隔符?

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

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

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" ;
}

看到

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

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";
}

现场演示