C++ not writing string to text file in proper format. This is the code
#include<iostream>
#include<fstream>
using namespace std;
class student
{
string name;
int roll;
float per;
public:
void put()
{
cout << "Name: " << name << endl;
cout << "Roll no.: " << roll << endl;
cout << "Percentage: " << per << endl;
cout << endl;
}
void get()
{
cout << "Enter your name: ";
cin >> name;
cout << "Enter your roll no.: ";
cin >> roll;
cout << "Enter your percentage: ";
cin >> per;
cout << endl;
}
};
int main()
{
student s;
fstream f;
int ch;
while(1)
{
cout<<"\n-------------------MENU-------------------\n";
cout<<"1.Add Record\n";
cout<<"2.Search\n";
cout<<"3.Delete\n";
cout<<"4.Modify\n";
cout<<"5.Display File\n";
cout<<"6.QUIT\n";
cout << "\nEnter your choice: ";
cin>>ch;
switch(ch)
{
case 1:
f.open("student.txt", ios::app);
s.get();
f.write((char*)&s, sizeof(s));
f.close();
break;
case 5:
f.open("student.txt", ios::in);
while (f.eof() != 0)
{
f.read((char*)&s, sizeof(s));
s.put();
}
f.close();
break;
case 6: cout << "Quiting\n";
return -1;
default: cout << "Invalid input";
}
}
return 0;
}
I want to write name, percentage & roll no. of student to the text file but it's writing it improperly (in binary I guess). How can I fix it? This is how the text file looks