C++ ofstream 换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9705923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:12:12  来源:igfitidea点击:

C++ ofstream line break

c++ofstreamline-breaks

提问by Pablo Canseco

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?

问题是, output.dat 中的所有内容都在同一行上。我该如何解决这个问题?

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.daton the Linux side to see the file contents would have revealed that Windows vs. Linux line breaks are different at the time.

编辑:我使用 Windows 查看文件并使用 Linux 进行编译。这就是我遇到这个问题的原因。使用cat output.dat在Linux中看到文件的内容会发现,Windows与Linux的换行符是在不同的时间。

采纳答案by thiton

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. unix2dosis your friend.

std::endl 已经插入了换行符,因此您的文件中有换行符。我假设您在 LF 系统(Linux 或其他类 UNIX)上生成文件并在 CRLF 系统上查看它。在这种情况下,您的换行符不会在文本编辑器中显示为换行符。unix2dos是你的朋友。

回答by Pablo Canseco

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

更换std::endl"\r\n"得到,而不是仅仅LF CRLF。