使用If语句/条件将数据输出到一个文件或另一个文件C++

Use If statement / conditional to output data to one file or another file C++

C++ 新手。我有一个 #define 变量(全局变量?不确定在 C++ 中这些是什么)我可以将其设置为 1 或 0。如果它 == 1,我希望我的代码将我的数据输出到“File_A.txt”。如果它 == 0,我希望我的代码将数据输出到“File_B.txt”。

我尝试在初始化输出文件时使用 if 语句:

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;
#define value 1
...
if (value == 1){
  ofstream fout("File_A.txt");
} else if (value == 0){
  ofstream fout("File_B.txt");
       }

但似乎这样做会使代码在我尝试关闭文件 fout << endl; 时无法将 fout 识别为输出文件标识符,而是认为 fout 是一个未声明的变量...当我尝试编译时,它 returns 经典错误 error: ‘fout’ was not declared in this scope.

感觉应该很简单吧,哈哈。让我知道是否需要提供更多细节。我尽量保持简短和直截了当。

谢谢

这是一个代码片段,基于 Sam Varshavchik 的评论:

std::ofstream fout; // Don't assign to a file yet.
//...
char const * p_filename = nullptr;
switch (value)
{
    case 0:  p_filename = "File_B.txt"; break;   
    case 1:  p_filename = "File_A.txt"; break;   
}
fout.open(p_filename);

在上面的例子中,首先根据value确定文件名,然后使用文件名打开文件流变量。

编辑 1:备选方案
另一种方法是先确定文件名,然后声明文件流:

char const * p_filename = nullptr;
switch (value)
{
    case 0:  p_filename = "File_B.txt"; break;   
    case 1:  p_filename = "File_A.txt"; break;   
}
std::ofstream fout(p_filename);