将对象直接流式传输到std :: string [英] Stream object directly into a std::string

查看:90
本文介绍了将对象直接流式传输到std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出某种可流式传输的类型:

Given some type that is streamable:

struct X {
    int i;

    friend std::ostream& operator<<(std::ostream& os, X const& x) {
        return os << "X(" << x.i << ')';
    }
};

我想将此附加到 std :: string 上.我可以这样实现:

I want to append this onto a std::string. I can implement this as:

void append(std::string& s, X const& x) {
    std::ostringstream os;
    os << x;
    s.append(os.str());
}

但是这似乎很me脚,因为我将数据写入一个流中只是为了分配一个新字符串,只是为了将其附加到另一个字符串上.有更直接的路线吗?

But this seems lame since I'm writing data into one stream just to then allocate a new string just for the purposes of appending it onto a different one. Is there a more direct route?

推荐答案

这可以通过新型标准C ++ IOStreams和语言环境:高级程序员指南和参考).

以下是它的外观草图:

#include <streambuf>

class existing_string_buf : public std::streambuf
{
public:
    // Store a pointer to to_append.
    explicit existing_string_buf(std::string &to_append); 

    virtual int_type overflow (int_type c) {
        // Push here to the string to_append.
    }
};

一旦您在此处充实了详细信息,就可以按以下方式使用它:

Once you flesh out the details here, you could use it as follows:

#include <iostream>

std::string s;
// Create a streambuf of the string s
existing_string_buf b(s);
// Create an ostream with the streambuf
std::ostream o(&b);

现在,您只需写入 o ,结果应显示为附加在 s 上.

Now you just write to o, and the result should appear as appended to s.

// This will append to s
o << 22;

修改

正如@rustyx正确指出的那样,需要重写 xsputn 来提高性能.

As @rustyx correctly notes, overriding xsputn is required for improving performance.

完整示例

以下打印为 22 :

#include <streambuf>
#include <string>
#include <ostream> 
#include <iostream>

class existing_string_buf : public std::streambuf
{
public:
    // Somehow store a pointer to to_append.
    explicit existing_string_buf(std::string &to_append) : 
        m_to_append(&to_append){}

    virtual int_type overflow (int_type c) {
        if (c != EOF) {
            m_to_append->push_back(c);
        }
        return c;
    }

    virtual std::streamsize xsputn (const char* s, std::streamsize n) {
        m_to_append->insert(m_to_append->end(), s, s + n);                                                                                 
        return n;
    }

private:
    std::string *m_to_append;
};


int main()
{   
    std::string s;
    existing_string_buf b(s);
    std::ostream o(&b);

    o << 22; 

    std::cout << s << std::endl;
}   

这篇关于将对象直接流式传输到std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆