I'm working on a project that basically writes into a file the contents of some objects's fields data I've created(one of them being pers1, of the class PERSON);
I've inserted data into the field members of the object pers1, and I opened a file, trying to write the content of those field members(string name, surname and unsigned int age) into the file, using file.write function. It wrote parts of the contents, inbetween alot of garbage. Please help me write the proper code, so that I can write each person details into the file in a consecutive way. Thank you
#include<iostream>
#include<string>
#include<fstream>
#include <sstream>
#include <iomanip>
#include <list>
class PERSON
{
string name;
string surname;
unsigned int age;
public:
void inputinfo()
{
cin>>name;
cin>>surname;
cin>>age;
}
outputinfo()
{
cout<<name;
cout<<surname;
cout<<age;
}
};
class STUDENT: public PERSON
{
int ID;
float marks_sum;
string belonging_class;
public:
inputinfo()
{
cin>>name;
cin>>surname;
cin>>age;
cin>>ID;
cin>>marks_sum;
cin>>belonging_class;
}
};
void writeinfile()
{
PERSON pers1;
ofstream file1
file1.open("Students.txt", std::ofstream::out | std::ofstream::app);
pers1.inputinfo();
file1.write(pers1.c_str(),pers1.length()); // this is the second aproach I've found on internet, but it gives errors;
file1.write((char*)&pers1, sizeof(pers1)); // this one is puting alot of garbage into the file, alongside fields data.
fisier.close();
}
int main
{
int opt1, opt2;
char option;
switch(opt1)
{
case 1:
do
{
cout<<endl;
<<"Choose one of variants"<<"1.Students"<<"2.Teachers"<<"3.Get back to main menu"<<endl;
cin>>opt2;
switch(opt2)
{
case 1:
do
{
cout<<"Do you wish to introduce a new student(Y/N)?";
cin>>option;
if(option!='N')
writeinfile()
} while(option!='N');
break;
default:
cout<<"Incorect!"<<endl;
}
while(opt2!=3);
break;
case 2: "...."
;
break
case 3: "...."
;
break;
}
}
}
I expect clean write of field data into the file, everytime I call the aforementioned function. For example for 1st iteration, when I enter data into the object's field: name : John, surname: Doe, age: 45, I espect to see this data into a single line in the file(and no garbage inbetween).