我想创建教育原因,C ++的ostream。我的测试将被创建的作用就像一个的ofstream将除外,而不是写入它将写入一个双端队列或载体容器的文件一个ostream。

有帮助吗?

解决方案

由于它是教育,就像你说的,我会告诉你我怎么会做这样的啄。否则,stringstream是真的要走的路。

听起来像是你想创建一个流缓冲的实现,然后写一个矢量/双端队列。像这样的东西(从我的另一个答案是复制一个目标的/ dev / null的流):

template<typename Ch, typename Traits = std::char_traits<Ch>,
         typename Sequence = std::vector<Ch> >
struct basic_seqbuf : std::basic_streambuf<Ch, Traits> {
     typedef std::basic_streambuf<Ch, Traits> base_type;
     typedef typename base_type::int_type int_type;
     typedef typename base_type::traits_type traits_type;

     virtual int_type overflow(int_type ch) {
         if(traits_type::eq_int_type(ch, traits_type::eof()))
             return traits_type::eof();
         c.push_back(traits_type::to_char_type(ch));
         return ch;
     }

    Sequence const& get_sequence() const {
        return c;
    }
protected:
    Sequence c;
};

// convenient typedefs
typedef basic_seqbuf<char> seqbuf;
typedef basic_seqbuf<wchar_t> wseqbuf;

可以使用这样的:

seqbuf s;
std::ostream os(&s);
os << "hello, i'm " << 22 << " years old" << std::endl;
std::vector<char> v = s.get_sequence();

如果你想有一个双端队列为顺序,你可以这样做:

typedef basic_seqbuf< char, char_traits<char>, std::deque<char> > dseq_buf;

或类似的东西...嗯,我没有测试它。但也许这也是一件好事 - 所以,如果它仍包含的错误,你可以尝试修复它们。

其他提示

使用std :: stringstream的

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream   s;
    s << "Plop" << 5;

    std::cout << s.str();
}

我就此话,你不必写的是一个ostream类类。您可以使用适配器来实现自己的目标。

例如,该代码从istream的读取,并且每个元件插入到载体中:

vector<string> V;
copy(istream_iterator<string>(cin), 
     istream_iterator<string>(), 
     back_inserter(V)); 

如果没有你想要做到这一点是很难过具体什么更多的细节,但你不希望创建一个新的ostream。你要做的是创建一个新型的流缓冲,并使用现有的ostream。

在easyist要做的事情是从STD继承:: basic_filebuf <>,和过载同步()和溢出()方法将元素添加到你的数据结构。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top