如何将数据写入单独的行中每个文件

How to write a data to file each in separate line?

本文关键字:文件 单独 数据      更新时间:2023-10-16

我想在单独的行中写入文件数据。代码如下所示:

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void writeToFile(const vector<double> &data){
    ofstream outFile("newData.txt", std::ofstream::binary);
    double num1 = 1, num2 = 2, num3 = 4;
    for (const auto &it : data) {
        outFile << it << endl;
    }
    outFile.close();
}
int main(){
    vector<double> data { 1, 2, 3, 4 };
    writeToFile(data);
    return 0;
}

"newData.txt"文件的输出为:

123

我想得到:

1
2
3

我使用 endl,但它不起作用。你知道怎么解决吗?谢谢。

不要对文本文件使用 std::ofstream::binary。打开方式:

ofstream outFile("newData.txt", std::ofstream::out);

或等效地只是:

ofstream outfile("newData.txt");

这是因为您正在以二进制模式打开文件。尝试 ofstream outFile("new.txt"),这将以文本模式打开文件,endl 现在应该在单独的行中写入数字。