What is wrong with the code below.It runs Perfectly fine for some inputs and crashes for some special inputs?
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct event {
string date,time,content;
bool is_high_priority;
};
int main() {
event one,two;
one.is_high_priority=false;
char tmp;
ofstream out_file("events" , ios::binary );
cout<<"\nEnter Date(dd.mm) ";
cin>>one.date;
cout<<"\nEnter Time(hh:mm:ss) ";
cin>>one.time;
cout<<"\nenter content";
cin>>one.content;
if(tmp == 't')
one.is_high_priority = true;
else
one.is_high_priority = false;
out_file.write((char*) &one, sizeof(one) );
out_file.close();
ifstream in_file("events" , ios::binary );
in_file.read((char*)&two,sizeof(two));
cout<<two.date<<" "<<two.time<<" "<<two.content<<" "<<two.is_high_priority;
in_file.close();
}
It crashed for these inputs :
Enter Date(dd.mm) ankmjjdn md
Enter Time(hh:mm:ss)
enter contentsnjs sjnsn
You can’t just save the bytes of a
std::stringobject to a file and later load them again. Thestd::stringcontains pointers to dynamically allocated memory, and your save/load will just duplicate the pointer itself, not the pointed to data.