在C ++中写入文本文件时使用布尔标志的问题

时间:2013-03-19 00:22:38

标签: c++

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

2 个答案:

答案 0 :(得分: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();
  }

}

答案 1 :(得分: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";
}
// ...