[英]Use If statement / conditional to output data to one file or another file C++
New to C++. C++ 的新手。 I have a #define variable (global variable? Not sure what these are called in C++) which I can set to a 1 or a 0. If it is == 1, I want my code to output my data to "File_A.txt".
我有一个#define 变量(全局变量?不确定这些在 C++ 中叫什么),我可以将其设置为 1 或 0。如果它是 == 1,我希望我的代码到 output 我的数据到“File_A.txt ”。 If it == 0, I want my code to output the data to "File_B.txt".
如果它 == 0,我希望我的代码到 output 数据到“File_B.txt”。
I tried to use an if statement when initializing the output file:我在初始化 output 文件时尝试使用 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");
}
but it seems like doing this makes the code not recognize fout
as the output file identifier when I try to close the file fout << endl;
但是当我尝试关闭文件
fout << endl;
时,似乎这样做会使代码无法将fout
识别为 output 文件标识符and rather it thinks that fout
is an undeclared variable... When I try to compile, it returns the classic error error: 'fout' was not declared in this scope
.而是它认为
fout
是一个未声明的变量...当我尝试编译时,它返回经典错误error: 'fout' was not declared in this scope
。
I feel like this should be pretty simple, haha.我觉得这应该很简单,哈哈。 Let me know if I need to supply more specifics.
如果我需要提供更多细节,请告诉我。 I tried to keep this brief and straight to the point.
我试图保持简短和直截了当。
Thanks谢谢
Here's a code fragment, based on Sam Varshavchik's comment:这是基于 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);
In the above example, the filename is determined first, based on value
, then the file stream variable is opened using the filename.在上面的示例中,首先根据
value
确定文件名,然后使用文件名打开文件 stream 变量。
Edit 1: Alternative编辑1:替代
An alternative is to determine the filename first, then declare the file stream:另一种方法是先确定文件名,然后声明文件 stream:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.