The purpose of this code is to support running my code either by ./a.out < input_file_name or just ./a.out input_file_name. I know I can wrap my reading part into a separate function with a parameter iostream&, so I can pass either ifstream or cin depending on whether argc == 2.
int main(int argc, char* argv[]) {
if (argc != 1 && argc != 2) {
cerr << "usage file or <file" << endl;
}
ifstream in;
if (argc == 2) {
in.open(argv[1]);
cin.rdbuf(in.rdbuf());
}
string line;
while (getline(cin, line))
cout << line << "\n";
}
My above trivial code always use cin read stuff. Do I need to set cin back to its original rdbuf?
Some code examples I found always set back rdbuf to its original value. Do we have to? Is there any resource leak when changing cin or cout's rdbuf without setting back its original rdbuf later?
You correctly suggest to wrap reading into a separate function, that gets either in or cin passed as parameter. That would be the best solution.
Besides that, to answer your question: You are not required to set it back; but you might harm other users this way. It's very unexpected, to read from some file using cin. The following users using cin in your program will have a hard time using cin as normal. If you want to keep your code, you probably should set it back.
Why not just do the following (leaving cin aside completely):
ifstream in;
if (argc > 2) {
in.open(argv[1]);
}
istream & input = (argc > 2 ? in : cin);
string line;
while (getline(input, line))
cout << line << "\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With