第一步检查文件是否打开,用到头文件:
#include <fstream>
#include <sstream>
文件打开的函数为
file.isopen()
信息输入到文件应该为
file << "" << value;
注意是file<<
如图
定义file
ofstream file(filename);
完整代码演示
void write_data_to_file(const string& filename, char separator, const Household* household, int household_number) {string files,x;ofstream file(filename);if (household == nullptr) {file << "A4;" << household_number << ";" << household->city << ";" << household->waterheating << ";" <<household->price_perKWh << endl;}if (!file.is_open()) {cout << "Error: Unable to open file for writing." << endl;return;}file << "A4;" << household_number << ";" << household->city << ";" << household->waterheating << ";"<< household->persons << ";" << household->squaremetres << endl;file << "household;" << household_number << ";" << household->city << ";" << household->waterheating << ";"<< household->persons << ";" << household->squaremetres << endl;cout << "Output file \"" << filename << "\" closed." << endl;
}
文件参数为:文件名,分隔符,变量,变量的长度,也可以简化使用,在主函数的调用如下
string filename;cout << "Input file name: ";
cin >> filename;char separator;
cout << "Input separator character: ";
cin >> separator;write_data_to_file(filename, separator, households[index], index);