[英]Problems using a boolean flag when writing to text file in 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();
}
在最外層范圍內聲明流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();
}
}
if
語句的塊引入了一個新范圍。 創建outfile
在該范圍內,它是在下面摧毀}
。 只需在if
塊之外定義outfile
:
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";
}
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.