c++ writing in files

Hi guys, I am having difficulties in writing in a file using C++.I can't figure out why I can not add another "persons surname" in my text file. In the if statement the part where I read the surname, it seem to be not taken into account.Thanks

PS: I can compile and run the code, I can add in my text file all the details (name,surname,age) for the first person, but if I want to add another person I can add only the name and age for that person.

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
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
#include<fstream> // fstream=Stream class to both read and write from/to files.
#include<conio.h>
#include<string>
using namespace std;


int main () {
             
   time_t now = time(0); // current date/time based on current system
   char* dt = ctime(&now);  // convert now to string form
   int persoana;
   string nume, prenume;
   int varsta;
   ofstream myfile;
   myfile.open ("file.txt");
   myfile<<"\t"<<"\t"<<"\t"<<dt<<endl;
  
 cout<<"Enter name :"<<endl;
 getline (cin,nume);
 myfile<<nume<<endl;
 
 cout<<"Enter surname:"<<endl;
 getline(cin,prenume);
 myfile<<prenume<<endl;
 
 cout<<"Enter age:"<<endl;
 cin>>varsta;
 myfile<<varsta<<endl;
 
 cout<<"Do you want to add a new person: 1 YES  2 NO"<<endl<<endl;
 cin>>persoana;
 
 if (persoana ==1) {
              cout<<"Enter name :"<<endl;
              getline (cin,nume);
              myfile<<nume<<endl;  
              
              
              cout<<"Enter surname:"<<endl;
              getline(cin,prenume);
              myfile<<prenume<<endl;
              
              cout<<"Enter age:"<<endl;
              cin>>varsta;
              myfile<<varsta<<endl;     
              
                                 
} else if  (persoana ==2) { cout<<"Thanks !";} 
 
  myfile.close();
  getch();
  return 0;
}
Try this.
write cin.ignore ();
Before line of 41
Last edited on
Thank you newbiee999
Topic archived. No new replies allowed.