adding a newline to file in C++
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 succe开发者_运维知识库ssfully 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 ?
#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 =)
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
:
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
use ios_base::app
instead (adding lines instead of overwriting):
#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 ;
}
精彩评论