将Ostream传入Istream [英] Pass Ostream into Istream

查看:493
本文介绍了将Ostream传入Istream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数用于将数据输出到ostream对象,以及一个构造函数,用于以完全相同的格式从istream对象初始化类。即

  std :: ostream& operator<<<<(std :: ostream& os,const Matrix& m){
//输出到os
}

,然后

  Matrix :: Matrix(std :: instream& in ){
//从中构造对象
}

我如何把输出的第一个输入到第二个?我已经尝试了很多东西,大多是试错误,但我完全失去(即使甚至不确定什么流类型使用)。感谢

解决方案

由于需要输入和输出,所以需要 std :: iostream ,它继承了 std :: istream std :: ostream 。听起来你想要使用一个内存缓冲区,而不是一个文件缓冲区,所以一个类型 std :: stringstream 的对象会做的伎俩。只要确保在使用它输入之前调用 stream.seekg(0,std :: ios :: beg)将流回绕到开头。 p>

此代码也可以重用于文件I / O,只需将 std :: fstream 改为相应的函数。但是由于写入和读取将被分开, std :: ofstream std :: ifstream 可能是更好的选择。


I have one function that outputs data into an ostream object, and a constructor that initializes a class from an istream object in the exact same format. i.e

std::ostream& operator<<(std::ostream &os, const Matrix &m) {
    // Output to os
}

and then

Matrix::Matrix(std::instream& in) {
    // Read from in to construct the object
}

so how to I push the output of the first to the input of the second? I have tried a lot of things, mostly trial and error, but am completely lost (i.e not even sure what stream type to use). Thanks

解决方案

Since you need both input and output, you need a derivative of std::iostream which inherits both std::istream and std::ostream. It sounds like you want to use a memory buffer, not a file buffer, so an object of type std::stringstream would do the trick. Just be sure to call stream.seekg(0, std::ios::beg) to "rewind" the stream back to the beginning before using it for input.

This code could also be reused for file I/O, simply by passing std::fstream instead to the respective functions. But since writing and reading would then be separated, std::ofstream and std::ifstream might be better choices.

这篇关于将Ostream传入Istream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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