C++ ofstream line break

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-29 12:19:34

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9705923/c-ofstream-line-break

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!