简体   繁体   中英

Problems using a boolean flag when writing to text file in C++

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.

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

Here's the troublesome code snippet:

#include <iostream>
#include <fstream>

int main()
  bool write_outfile = true;

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

// Do some other stuff here

  if (write_outfile)
  {
        outfile.close();
  }

Declare ofstream outfile in the outermost scope. Otherwise, it's only defined in the first if-statement. That is:

#include <iostream>
#include <fstream>

int main() {
  bool write_outfile = true;
  ofstream outfile;

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

// Do some other stuff here

  if (write_outfile)
  {
        outfile.close();
  }

}

The block of an if statement introduces a new scope. You create outfile in that scope and it is destroyed at the following } . Simply define outfile outside the if block:

bool write_outfile = true;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM