Conditionally reading file from std input or a file
<p>Newbie C++ programmer here. I'm trying to write a command line application that takes two arguments, an input file and an output file. However, if the input file or the output file name is "-", I need the program to read/output to standard input/output instead. My problem is that in C++, I don't know how to do this without the compiler not knowing that the input/output streams are initialized. Here's the code I have.</p>

<pre><code>if(argv[1] == "-") {
  istream input;
  cout &lt;&lt; "Using standard input" &lt;&lt; endl;
}
else {
  ifstream input;
  cout &lt;&lt; "Using input file " &lt;&lt; argv[1] &lt;&lt; endl;
  input.open(argv[1], ios::in);
  if(!input) {
    cerr &lt;&lt; "Cannot open input file '" &lt;&lt; argv[1]
    &lt;&lt; "', it either does not exist or is not readable." &lt;&lt; endl;
    return 0;
  }
}

if(argv[2] == "-") {
  ostream output;
  cout &lt;&lt; "Using standard output" &lt;&lt; endl;
}
else {
  ofstream output;
  cout &lt;&lt; "Using output file " &lt;&lt; argv[2] &lt;&lt; endl;
  output.open(argv[2], ios::out);

  if(!output) {
    cerr &lt;&lt; "Cannot open output file '" &lt;&lt; argv[2] &lt;&lt; "' for writing."
    &lt;&lt; " Is it read only?" &lt;&lt; endl;
    return 0;
  }
}
</code></pre>

<p>From here I cannot call the operator >> on input, because, I'm guessing, the compiler doesn't know it's been initialized.</p>
