I would like to parse either an stdin
stream or a file. So I want a function/method to accept either of this.
Note that my goal is not to call read
twice!
As istream
is the base class for cin and
ifstream` I should be able write this:
#include <iostream>
#include <fstream>
void read(std::istream &fp) {
while(!fp.eof()) {
std::string line;
std::getline(fp, line);
std::cout << line << std::endl;;
}
}
int main(int argc, char *argv[])
{
std::ifstream fp;
if (argc >= 2) {
fp.open(argv[1]);
if (!fp) abort();
}
else {
fp = std::cin;
}
read(fp);
if (fp.is_open()) {
fp.close();
}
return 0;
}
In C I can do the following with calling it with either read_content(stdin)
or read_content(fp)
:
void read_content(FILE *file)
What is the proper way to do this in C++?