Problems using a boolean flag when writing to text file in C++
<p>I am learning the syntax and nuances of reading/writing to files. Here's my problem. If my code writes to a file based on a user flag (write_outfile = true), then my attempt to close the file at the end results in an "undefined identifier" error. </p>

<p>However if I open and then close the file within the same "if" statement then things are fine.</p>

<p>Here's the troublesome code snippet:</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;fstream&gt;

int main()
  bool write_outfile = true;

  if (write_outfile)
  {
    ofstream outfile;
    outfile.open("output_test.txt");
    outfile &lt;&lt; "This is my first text file written from C++.\n";
  }

// Do some other stuff here

  if (write_outfile)
  {
        outfile.close();
  }
</code></pre>
