Pablo Canseco
Pablo Canseco

Reputation: 562

C++ ofstream line break

This is my code:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream ifile ("input.dat", ios::in);
    ofstream ofile ("output.dat",ios::out);

    int num;
    ifile >> num;
    ofile << num;
    ofile << endl;
    ofile << "Did we go to new line?";
    ofile << endl;

    return 0;
}

The problem is, everything in output.dat is on the same line. How can I resolve this?

Thanks!

EDIT: I was using Windows to see the files and Linux to compile. This is why I was running into this issue. Using cat output.dat on the Linux side to see the file contents would have revealed that Windows vs. Linux line breaks are different at the time.

Upvotes: 9

Views: 36301

Answers (2)

user677656
user677656

Reputation:

Replace std::endl with "\r\n" to get CRLF instead of just LF.

Upvotes: 7

thiton
thiton

Reputation: 36049

std::endl already inserts a linebreak, so you have linebreaks in your file. I assume you are generating your file on a LF system (Linux or other UNIX-like) and viewing it on a CRLF system. In this case, your linebreak won't show in the text editor as a linebreak. unix2dos is your friend.

Upvotes: 2

Related Questions