2011-03-21 30 views
3

任何机构可以帮助我处理这个简单的事情吗?在C++中添加一个换行符到文件

下面是我的代码:

#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 ; 
} 

它成功运行,现在,我想按照我的方式来设置文本格式文件的输出。

我:

你好,这是第一个程序我写这是一个实验

我怎样才能让我的输出文件如下所示:

嗨,这是第一个程序

我的作家,这是一个实验

我应该怎么做格式化以这种方式输出?

回答

0

首先,你需要打开流写入到文件:

ofstream file; // out file stream 
file.open("anish.txt"); 

之后,你可以写文件中使用<<操作:

file << "hi this is first program i writer"; 

此外,使用std::endl代替的\n

file << "hi this is first program i writer" << endl << "this is an experiment"; 
+6

如果您希望打印行后刷新输出,请使用std :: endl。否则'\ n'更可取。经常刷新缓冲区可能导致次优磁盘访问。 – 2011-03-21 04:51:23

+0

这在Windows XP中有什么不同? endl和“\ n”都显示为我的文本文件中意义未知字符的小空矩形? – Instinct 2014-02-14 00:02:47

+0

“*首先你需要打开流写入文件*” - 将文件名传递给std :: ofstream'构造函数立即打开文件,不需要单独调用open()。 – 2018-01-24 19:51:00

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(); 
} 

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

+1

1使用ENDL的典型的C++成语新线。 – 2011-03-21 04:34:28

+0

我有类似的代码制作一个新的流文件,打开它,然后写入它,但“\ n”和<< endl由于某种原因不工作。我只是得到了一个小矩形框,意思是它不能识别字符,不知道这是由于运行Windows XP还是什么? – Instinct 2014-02-13 23:56:00

+0

在Windows上,标准换行符是'\ r \ n',而不是'\ n'。如果流在文本模式下打开(默认),'std :: ofstream' *应该*自动将'\ n'转换为OS的标准换行符。如果这没有发生,那么你要么以二进制模式打开流,要么你有一个错误的STL实现。至于'std :: endl',它只是将一个'\ n'字符写入流中,然后刷新流。 – 2018-01-24 19:55:17

相关问题