我正在学习读/写文件的语法和细微差别。这是我的问题。如果我的代码基于用户标志 (write_outfile = true) 写入文件,那么我在最后关闭文件的尝试会导致“未定义标识符”错误。
但是,如果我在同一个“if”语句中打开然后关闭文件,那么一切都很好。
这是麻烦的代码片段:
#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();
  }