[英]Use If statement / conditional to output data to one file or another file C++
C++ 的新手。 我有一個#define 變量(全局變量?不確定這些在 C++ 中叫什么),我可以將其設置為 1 或 0。如果它是 == 1,我希望我的代碼到 output 我的數據到“File_A.txt ”。 如果它 == 0,我希望我的代碼到 output 數據到“File_B.txt”。
我在初始化 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");
}
但是當我嘗試關閉文件fout << endl;
時,似乎這樣做會使代碼無法將fout
識別為 output 文件標識符而是它認為fout
是一個未聲明的變量...當我嘗試編譯時,它返回經典錯誤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
確定文件名,然后使用文件名打開文件 stream 變量。
編輯1:替代
另一種方法是先確定文件名,然后聲明文件 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.