Adding a new line to a file in C ++

Can any body help me with this simple thing in processing files?

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

Now it works successfully, I want to format the output of a text file in accordance with my method.

I have:

hi this is the first program i writer, this is an experiment

How to make the output file as follows:

hi is the first program

     

I write that this is an experiment

What should I do to format the output in this way?

+3
source share
2 answers

First you need to open the stream to write to the 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::endlinstead \n:

file << "hi this is first program i writer" << endl << "this is an experiment";
+1
source
#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();
}

, , , =)

+11

All Articles