C++将信息输入到文件内

发布时间:2024年01月21日

第一步检查文件是否打开,用到头文件:

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

文章来源:https://blog.csdn.net/2301_77482405/article/details/135722497
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。