Jump to content

ofstream by default inputting a newline character when writing data to a file in cpp

Souranil21 chakraborty

<

int write_file(ofstream& writerhead){
//ofstream don't have any copy constructor so wee need to pass a reference instead of the direct object.
string inp;
cout<<"Give what you want to write in the file: ";
getline(cin,inp,'~');
writerhead << inp;
return writerhead.goodbit;
}

>

 

<

{ofstream outputfile(filename);
if(!write_file(outputfile)){
cout<<"Data written successfully.\n";
outputfile.close();
}
else{
cout<<"The data couldn't be written to the file successfully.\nSome internal error in writing the data.\n";
}}

>

 

The first part is the function that actually is writing the  data and second part is in the main function choice for writing new data to the file instead of appending to the existing data in the file.So whenever i am taking input from the user for writing to the file getline(cin,inp,'~') is automatically inserting a new line character in the starting position that's why every time i append or write to the file there is an additional newline and the first line is being skipped.

Link to comment
Share on other sites

Link to post
Share on other sites

To append data written to the file with ofstream set the mode to append mode using std::base_io::app

ofstream outputfile(filename, std::ios_base::app); // <-- ofstream append mode

 

 

Tip when posting code in your post press the angle bracket button in post editor.

image.png.8e67aa0b571e5ba353357e1a52b5530e.png

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×