How should I read from a file if there is one given as a command line argument, if not I would like to read from std::cin. I tried to solve this with pointers to istrem, but is there a better way.
Asked
Active
Viewed 499 times
-1
-
41) "_I tried to solve this with pointers to istrem_" Why would you need to use pointers to `std::ifstream`? 2) Please show [mcve] with an actual question. SO is **not** code writing service. – Algirdas Preidžius Jul 23 '18 at 13:01
-
1@DevSolar Does not look like a duplicate. – zdf Jul 23 '18 at 13:38
3 Answers
2
You probably tried to use a pointer to istream
to have it point to either an std::fstream
instance or to std::cin
depending on the command line parameters.
It would be better as a reference:
int main(int argc, char *argv[])
{
std::fstream fin;
if (argc > 1)
fin.open(argv[1]);
std::istream &in = fin.is_open() ? fin : std::cin;
// ... continue using `in`
}

acraig5075
- 10,588
- 3
- 31
- 50
0
ifstream
derives from istream
. So if a file is given on the command line then you open the file and use the resulting ifstream as istream. Otherwise you use std::cin.

Goswin von Brederlow
- 11,875
- 2
- 24
- 42
-2
Check this : How do you open a file in C++?
With the exception that path_to_file is an input coming from std::cin or command line argument.

Domenico Paolicelli
- 97
- 3
- 6
-
If the answer to the question, is present in another SO question, one should flag as duplicate, **not** to post his own answer linking to another one.. – Algirdas Preidžius Jul 23 '18 at 13:06