任何人都可以帮助我处理文件处理中的这个简单的事情吗?
以下是我的代码:
#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 ;
}
现在运行成功了,我想按照我的方式格式化文本文件的输出
我有:
hi this is first program i writer this is an experiment
如何使我的输出文件如下所示:
hi this is first program
I writer this is an experiment
我应该怎么做才能以这种方式格式化输出?
#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();
}
再一次,希望这就是你想要的=)
首先,您需要打开流以写入文件:
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";
// 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
使用
ios_base::app
代替(添加行而不是覆盖):
#include<fstream>
using namespace std;
int main()
{
ofstream savefile("anish.txt", ios_base::app);
savefile<<"hi this is first program i writer" <<"\n this is an experiment";
savefile.close();
return 0 ;
}