3

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

Lobe
  • 528
  • 10
  • 25
  • 2
    It depends on the type of data you're passing. If you're outputting it to the screen, chances are you're turning it into some sort of string, therefore you would use a stringstream. –  Sep 12 '13 at 02:30
  • It is a human readable format of the object that can also be used to initialize new objects. Stringstream sounds like a good idea – Lobe Sep 12 '13 at 02:43
  • Why on earth would you push teh result of the one into the other? Just make a copy constructor! – Mooing Duck Sep 12 '13 at 03:07
  • haha, I didn't design this. The idea is to have a comprehendable format that could be saved to file. For the sake of testing I just want to bypass all work with files for the time being. There is also a copy constructor which will be used for copying. – Lobe Sep 12 '13 at 03:17

1 Answers1

6

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.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • Could you clarify the "rewind the stream" part? What happens when doing `stream.seekg(0, std::ios::beg)` and why is it necessary before using the stream for input? – helmesjo Dec 13 '18 at 09:42
  • 1
    @helmesjo There is only one current position in the stream, shared by reading and writing. Switching from writing to reading without a seek in-between is UB. So if you write some text into an empty file, and then immediately attempt to read, the result could be empty (because the position is at the end) or garbage (because UB). – Potatoswatter Dec 13 '18 at 19:41