在 C++ 中向文件添加换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5373766/
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
adding a newline to file in C++
提问by user513164
Can any body help me with this simple thing in file handling?
任何机构都可以帮助我处理文件处理中的这个简单事情吗?
The following is my code:
以下是我的代码:
#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 ;
}
It is running successfully now, I want to format the output of the text file according to my way.
现在运行成功,我想按照我的方式格式化文本文件的输出。
I have:
我有:
hi this is first program i writer this is an experiment
嗨,这是我写的第一个程序,这是一个实验
How can I make my output file look like the following:
如何使我的输出文件如下所示:
hi this is first program
I writer this is an experiment
嗨,这是第一个程序
我写这是一个实验
What should I do to format the output in that way ?
我应该怎么做才能以这种方式格式化输出?
采纳答案by Gunnar Schigel
First, you need to open the stream to write to a file:
首先,您需要打开流以写入文件:
ofstream file; // out file stream
file.open("anish.txt");
After that, you can write to the file using the <<
operator:
之后,您可以使用<<
运算符写入文件:
file << "hi this is first program i writer";
Also, use std::endl
instead of \n
:
另外,使用std::endl
代替\n
:
file << "hi this is first program i writer" << endl << "this is an experiment";
回答by ultifinitus
#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();
}
Again, hopefully this is what you want =)
再次,希望这是你想要的 =)
回答by Zia Khan
// Editor: MS visual studio 2019
// file name in the same directory where c++ project is created
// is polt ( a text file , .txt)
//polynomial1 and polynomial2 were already written
//I just wrote the result manually to show how to write data in file
// in new line after the old/already data
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("poly.txt", ios::out | ios::app);
if (!file) {
cout << "File does not exist\n";
}
else
{
cout << "Writing\n";
file << "\nResult: 4x4 + 6x3 + 56x2 + 33x1 + 3x0";
}
system("pause");
return 0;
}
**OUTPUT:** after running the data in the file would be
polynomial1: 2x3 + 56x2-1x1+3x0
polynomial2: 4x4+4x3+34x1+x0
Result: 4x4 + 6x3 + 56x2 + 33x1 + 3x0
The code is contributed by Zia Khan