0

I want to do something like this but keep running into an error, regarding the copy assignment operator for istream is protected. I want to have a way to switch input from cin to input from a file at some unknown point in my program.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
   istream &in = cin;
   ifstream f{"file.txt"};
   in = f;
   // Then I want to read input from the file.
   string s;
   while(in >> s) {
     cout << s << endl;
   }
}
Jack Gore
  • 3,874
  • 1
  • 23
  • 32
  • Streams are not assignable/copyable. What exactly are you trying to accomplish with `in=f;`? This makes no sense. Just use `operator>>` on `f` directly. – Sam Varshavchik Nov 19 '16 at 18:29

2 Answers2

3

You can't "copy a stream". A stream is not a container; it is a flow of data.

What you appear to really be trying to do is to rebind a reference. Well, you can't do that either (there's literally no syntax for it, hence your compiler thinks you're trying to copy-assign the stream itself), so use a pointer instead:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
   istream* in = &cin;
   ifstream f{"file.txt"};
   in = &f;
   // Now you can read input from the file.
   string s;
   while(*in >> s) {
     cout << s << endl;
   }
}

Make sure that f survives for as long as in is pointing to it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

You can achieve what you want by reassigning stream buffers with rdbuf:

in.rdbuf(f.rdbuf());

demo

krzaq
  • 16,240
  • 4
  • 46
  • 61