简体   繁体   中英

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

New to 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". If it == 0, I want my code to output the data to "File_B.txt".

I tried to use an if statement when initializing the output file:

#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;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 .

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:

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.

Edit 1: Alternative
An alternative is to determine the filename first, then declare the file 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM