1

我正在学习读/写文件的语法和细微差别。这是我的问题。如果我的代码基于用户标志 (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();
  }
4

2 回答 2

3

ofstream outfile在最外层范围内声明。否则,它只在第一个 if 语句中定义。那是:

#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();
  }

}

于 2013-03-19T00:24:37.240 回答
1

if语句块引入了一个新范围。您outfile在该范围内创建,它在以下被销毁}。只需在块outfile外定义:if

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";
}
// ...
于 2013-03-19T00:25:04.243 回答