Declaring generic istream in C ++

I need to write a program that reads from either ifstream or cin, depending on the parameters passed to the program at runtime.

I planned to do the following:

 istream in;

 if(argv[1] == "cin")
 {
      in = cin;
 }
 else
 {
      ifStream inFile;
      inFile.open(argv[1].c_str());
      in = inFile;
 }

However, istream is protected, and I cannot declare istream in. Is there a way to declare such a shared thread in a thread?

+3
source share
3 answers

istream*. , , . , , . , "inFile" ​​, . :

 istream* in;
 ifStream inFile;

 if(!strcmp(argv[1],"cin"))
 {
      in = &cin;
 }
 else
 {
      inFile.open(argv[1]);
      in = &inFile;
 }
 // use *in

( . .)

+3

cin, , . , , .

,

program.exe cin

program.exe

program.exe myfile.txt

program.exe < myfile.txt

* nix Windows.

+1

:

ifStream inFile;
istream in( argv[1] == "cin" ? cin : inFile.open(argv[1]));
0

Source: https://habr.com/ru/post/1731806/


All Articles