Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Ostream into Istream

Tags:

c++

stream

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::istream& in) {
    // Read from in to construct the object
}

so how do I push the output of the first function 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

like image 287
Lobe Avatar asked Oct 21 '25 06:10

Lobe


1 Answers

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.

like image 124
Potatoswatter Avatar answered Oct 23 '25 19:10

Potatoswatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!