简体   繁体   中英

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

I would like to write to file data each in separate line. The code is show below:

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

The output of the "newData.txt" file is:

123

I would like to get:

1
2
3

I use endl, but it doesn't work. Have you some idea how to solve it? Thanks.

Don't use std::ofstream::binary for text files. Open as:

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

or equivalently just:

ofstream outfile("newData.txt");

Its because you are opening the file in binary mode. Try ofstream outFile("new.txt"), this will open the file in text mode and endl should now write numbers in separate line.

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