在C++中向文件添加换行符

use*_*164 3 c++ file-io

在文件处理中,任何人都可以帮我解决这个简单的问题吗?

以下是我的代码:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ofstream savefile("anish.txt");
 savefile<<"hi this is first program i writer" <<"\n this is an experiment";
 savefile.close();
  return 0 ;
 }
Run Code Online (Sandbox Code Playgroud)

它现在运行成功,我想根据我的方式格式化文本文件的输出.

我有:

嗨这是第一个程序我作家这是一个实验

如何使输出文件如下所示:

嗨这是第一个程序

我作家这是一个实验

如何以这种方式格式化输出?

ult*_*tus 11

#include <fstream>
using namespace std;

int main(){
 fstream file;
 file.open("source\\file.ext",ios::out|ios::binary);
 file << "Line 1 goes here \n\n line 2 goes here";

 // or

 file << "Line 1";
 file << endl << endl;
 file << "Line 2";
 file.close();
}
Run Code Online (Sandbox Code Playgroud)

再次,希望这是你想要的=)


Gun*_*gel 3

首先,您需要打开流以写入文件:

ofstream file; // out file stream
file.open("anish.txt");
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用<<运算符写入文件:

file << "hi this is first program i writer";
Run Code Online (Sandbox Code Playgroud)

另外,使用std::endl而不是\n

file << "hi this is first program i writer" << endl << "this is an experiment";
Run Code Online (Sandbox Code Playgroud)

  • 如果您希望在打印一行后刷新输出,请使用 std::endl 。否则最好使用 '\n'。经常刷新缓冲区可能会导致磁盘访问不理想。 (9认同)
  • “*首先您需要打开流来写入文件*” - 将文件名传递给 `std::ofstream` 构造函数会立即打开文件,无需单独调用 `open()`。 (4认同)