txt file (i'm in emergency)

hi I wanna make a text file in my program and I want to insert 2 names and 2 numbers to it but I have a problem that when I add a new data the perivious one is gone. please it's an emergency

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  #include <iostream>
#include <fstream>
#include<string>
using namespace std;

int main () {
int x,j,k;

do{
	
string a,b;//a,b are names
cin>>a>>b;
cin>>j>>k>>x;//j,k are numbers
//x=1 is to add data x=0 to show data x!=2 is to end the program
	if(x==1){
	  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << a<<j<<endl;
    myfile << b<<k<<endl;
    myfile.close();
  }
  else cout << "Unable to open file";
}
  if(x==0){
  	string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 
  }

}while(x!=2);

  return 0;
}
When you write into the file, you are erasing all existing contents. You need to add a parameter when you write so you would not overwrite the contents. http://www.cplusplus.com/reference/fstream/ofstream/open/
Hengry is correct, here's a more concrete example.

ofstream myfile("example.txt", std::ios::app | std::ios::out);
Topic archived. No new replies allowed.