I need to write a program that reads in either from ifstream or cin, depending on parameters passed into the program at runtime.
I was planning on doing the following:
istream in;
if(argv[1] == "cin")
{
in = cin;
}
else
{
ifStream inFile;
inFile.open(argv[1].c_str());
in = inFile;
}
However, istream in protected, and I can’t declare istream in. Is there a way to declare such a generic in stream?
Try with an
istream*instead. Note, however, that you have to change your code slightly. Using pointers you have to preserve the memory area of the object that you’re pointing. In other words, the “inFile” variable cannot be declared there, as it won’t exist out of the else. The code could be, then:(Note also the modifications in the string handling. I modified them as an example.)