mardi 20 novembre 2018

Cannot write objects containing Strings to File

I am working on a phone book project in C++. I made a class and have string objects inside to store some strings.

My Program is unable to write the string data into the file and is troubling me. It only shows me the last data inserted.

Here is the sample program giving the basic idea of what I want to do and where does the problem reside.

#include <iostream>
#include <fstream>
using namespace std;

class student {
private:
    string name;    int age;    string mail;
public:
    void getData(student &s) {
        ofstream file;
        file.open("file.txt",ios::app);
        if(!file) {
            cout<<"Error in creating file.."<<endl;
            return;
        }
        cout<<"\nFile created successfully."<<endl;
        cout<<"Enter name:    ";cin.ignore(); getline(cin, name);
        cout<<"Enter age:     ";cin>>age;
        cout<<"Enter mail:    ";cin.ignore(); getline(cin, mail);
        file.write((char*)&s,sizeof(s));
        file.close();
        cout<<"\nFile saved and closed succesfully."<<endl;
    }
    void showData(student &s) {
        ifstream file1;
        file1.open("file.txt",ios::in);
        if(!file1){
            cout<<"Error in opening file..";
            return;
        }
        while(!file1.eof()){
             file1.read((char*)&s,sizeof(s));
             cout<<"Name: "<<name<<"\nAge : "<<age<<"\nMail: "<<mail<<endl; 
        }
        file1.close();
    }
};
int main() {
    student s;
    s.getData(s);
    s.getData(s);
    s.getData(s);
    s.showData(s);
    return 0;
}

I need help in this case.

Output Image

Aucun commentaire:

Enregistrer un commentaire