I wanna design an object that read from either file or console. If there is a command line argument, this argument is assumed to be a filename and the code will read from the file. Otherwise, the code will read from standard console cin. Since both ifstream object and cin are derived from istream, I would like to store in the class a istream& reference to either the ifstream object or to cin. Below is the code of the class:
#include <iostream>
#include <fstream>
#include <sstream>
class Reader {
public:
Reader(std::istream& is) : is(is) {}
private:
std::istream& is;
};
But I encountered a problem when trying to create such an object according to conditions at run-time. An attempt is as follows:
int main(int argc, char *argv[]) {
if (argc > 1) { //read from file
std::ifstream in_f(argv[1]);
if (in_f)
LineReader reader(in_f);
}
else { //read from console (standard input)
LineReader reader(std::cin);
}
//work on reader ...
return 0;
}
The thing is, the Reader object is constructed in the conditional statement. It will disappear after the execution goes out. But I need this object to do a lot of work after its construction. So I should define a Reader object outside the condition, but I can see no way to initialize it before the condition. I also have no idea how to "assign" a reference to istream after initialization because reference can't be changed. Note in addition that istream class can't be copied. So could you please teach me how to write the Reader class if I wanna store a reference to istream, and initialize it according to condition at run-time? My idea is that the code for handling the input, either from console or file, are exactly the same. I wanna reuse a single variable to represent the input stream of different type. Thank you.
PS: I am using C++11, and the code will be run in both Windows and Ubuntu.
Aucun commentaire:
Enregistrer un commentaire