A part of my program has two possible cases: (1) if the user only gives 2 command line arguments, take input from standard input (cin) (2) if the user gives 3 command line arguments (the last one being a file name), take input from the file. In order to not be reusing the same code for for both options, I tried to use a pointer to a superclass of both cin and ifstream, istream for both means of input.
My issue is that on lines 5 and 22 of the code below, I'm trying to reference methods only available to the subclass ifstream (open and close). Based on my logic, if those methods are called the pointer has to be pointing to a type ifstream, but the program fails to compile because those methods aren't defined in the istream class.
Is there any way to get around this?
istream *currentStream;
if (argc == 3) {
// Handle optional file input
currentStream = new ifstream(argv[2]);
currentStream->open(argv[2]);
if (currentStream->fail()) {
cerr << "FILE COULD NOT BE OPENED\n";
return 1;
}
} else {
currentStream = &cin;
}
string myLine;
// go line by line and translate it
while (getline(*currentStream, myLine)) {
if (currentStream->eof()) {
break;
}
cout << rot13(myLine) << endl;
}
if (dynamic_cast<ifstream*>(currentStream)) {
currentStream->close();
}
// handle pointer
delete currentStream;
currentStream = NULL;
return 0;