-1

In C++ I have made a program which writes given data into a text file (notepad). The problem is when I restart my program and enter other data then it clears the previous one and adds new data.

I want to keep my previous data safe, and add new data in a new line in text file.

For example,

I wrote "I am a programmer" in my program. Now my text file will show this:I am a programmer

Now if I restart my program and write "I am unemployed". Then textfile shows this: I am unemployed.

But I want my file to be:

I am a programmer

I am unemployed

Please, Help...

Michael Benjamin
  • 265,915
  • 79
  • 461
  • 583
Jatin
  • 71
  • 9

1 Answers1

-1

You need to open the file with the append flag. If you're using fstream, it looks something like this:

#include<fstream>
using namespace std;

fstream outfile = fstream("myfilename.txt", ios_base::app)

See reference http://www.cplusplus.com/reference/fstream/fstream/open/

user2647513
  • 524
  • 3
  • 12
  • `fstream.h` is outdated, so you should be using just ``, and `using namespace std;` should not be used that much. Also, why are you allocating the class on the heap? This means that the file has to be deleted eventually. – Arnav Borborah Aug 11 '16 at 15:54
  • Is it not good practice to use 'code' using namespace std 'code' in isolated code examples where it makes things easier to read? Other suggestions noted and answer revised. – user2647513 Aug 11 '16 at 16:10