user3603858
user3603858

Reputation: 619

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.

Upvotes: 0

Views: 3092

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

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

Upvotes: 2

littlie
littlie

Reputation: 21

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.

Upvotes: 1

Related Questions