Is there a way a string could be used instead of a char[] array in the below struct, and still be saved to a file using read and write functions without getting a runtime error?
#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
struct details
{
char name[30];
int add_year;
};
const char * file = "students.dat";
int main()
{
details x;
ifstream ifile;
ifile.open(file,ios_base::in|ios_base::binary);
if(ifile.is_open())
{
cout<<"Contents of "<<file<<" is"<<endl;
while(ifile.read((char *)&x,sizeof x))
{
cout<<x.name<<" - "<<x.add_year<<endl;
}
ifile.close();
}
ofstream ofile(file,ios_base::out|ios_base::app|ios_base::binary);
if(!ofile.is_open())
{
cerr<<"Can't open "<<file<<endl;
exit(EXIT_FAILURE);
}
cout<<"Name"<<endl;
cin.get(x.name,30);
cout<<"Year added"<<endl;
cin>>x.add_year;
ofile.write((char *) &x, sizeof x);
ofile.close();
cin.get();
return 0;
}