Read from cin or a file

m42a picture m42a · Mar 9, 2010 · Viewed 13.9k times · Source

When I try to compile the code

istream in;
if (argc==1)
        in=cin;
else
{
        ifstream ifn(argv[1]);
        in=ifn;
}

gcc fails, complaining that operator= is private. Is there any way to set an istream to different values based on a condition?

Answer

dmcer picture dmcer · Mar 9, 2010

You could use a pointer for in, e.g.:

istream *in;
ifstream ifn;

if (argc==1) {
     in=&cin;
} else {
     ifn.open(argv[1]);
     in=&ifn;
}