Read from cin or a file

前端 未结 4 1258
一向
一向 2021-01-18 03:29

When I try to compile the code

istream in;
if (argc==1)
        in=cin;
else
{
        ifstream ifn(argv[1]);
        in=ifn;
}

gcc fails,

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-18 04:18

    You cannot affect streams like this. What you want to achieve can be obtained using a pointer to an istream though.

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
      istream *in;
      // Must be declared here for scope reasons
      ifstream ifn;
    
      // No argument, use cin
      if (argc == 1) in = &cin;
      // Argument given, open the file and use it
      else {
        ifn.open(argv[1]);
        in = &ifn;
      }
      return 0;
    
      // You can now use 'in'
      // ...
    }
    

提交回复
热议问题