C
Christof Warlich
Hi,
I want my program to either read from cin or from a file, if present.
Below is the solution I ended up with, but it really looks clumpsy.
Couldn't this be done in a more elegant way?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
if(argc > 2) {
cerr << argv[0] << " is a filter or expects one input file.\n";
exit(EXIT_FAILURE);
}
ifstream instream;
istream *tmp;
if(argc == 2) {
instream.open (argv[1], fstream::in);
if(instream.fail()) {
cerr << "Failed to open file " << argv[1] << ".\n";
exit(EXIT_FAILURE);
}
tmp = &instream;
}
else {
tmp = &cin;
}
istream &in = *tmp;
string line;
while(getline(in, line)) {
// do something, e.g.:
cout << line << endl;
}
if(argc == 2) {
instream.close();
}
}
Thanks for any suggestions,
Christof
I want my program to either read from cin or from a file, if present.
Below is the solution I ended up with, but it really looks clumpsy.
Couldn't this be done in a more elegant way?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
if(argc > 2) {
cerr << argv[0] << " is a filter or expects one input file.\n";
exit(EXIT_FAILURE);
}
ifstream instream;
istream *tmp;
if(argc == 2) {
instream.open (argv[1], fstream::in);
if(instream.fail()) {
cerr << "Failed to open file " << argv[1] << ".\n";
exit(EXIT_FAILURE);
}
tmp = &instream;
}
else {
tmp = &cin;
}
istream &in = *tmp;
string line;
while(getline(in, line)) {
// do something, e.g.:
cout << line << endl;
}
if(argc == 2) {
instream.close();
}
}
Thanks for any suggestions,
Christof