Read from cin or a file

前端 未结 4 1259
一向
一向 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:10

    You can replace cin's streambuf with another, and in some programs this is simpler than the general strategy of passing around istreams without referring to cin directly.

    int main(int argc, char* argv[]) {
      ifstream input;
      streambuf* orig_cin = 0;
      if (argc >= 2) {
        input.open(argv[1]);
        if (!input) return 1;
        orig_cin = cin.rdbuf(input.rdbuf());
        cin.tie(0); // tied to cout by default
      }
    
      try {
        // normal program using cin
      }
      catch (...) {
        if (orig_cin) cin.rdbuf(orig_cin);
        throw;
      }
    
      return 0;
    }
    

    Even though it's extremely rare to use cin after control leaves main, the above try-catch avoids undefined behavior if that's something your program might do.

提交回复
热议问题