Posts Tagged ‘fault’

Parked at the Matzoh Fault Line

Friday, February 3rd, 2012

Parked at the Matzoh Fault Line
ho model trains
Image by ShellyS
#229 on Explore (4/13/09) Woohoo! And I was sure it was gonna be the sunbather! 🙂 Thanks, all.

Help with c++ assignment- structures and data files – causes segmentation fault?

Wednesday, September 21st, 2011

Question by Yoni R: Help with c++ assignment- structures and data files – causes segmentation fault?
using namespace std;

struct Cars // Cars structure
string name;
string make;
string model;
string drive_train;
string color;
int miles;

int main(int argc, char *argv[])
char ch;
string datatypechoice;
cout << "Press one of the following numbers followed by enter to choose what to do:\n\n1. Add to Cars\n2. Read from Cars\n"; cin >> datatypechoice;
if (datatypechoice == “1”)
Cars data;
cout << "Enter the name of the car: "; cin >>;
cout << "Enter the make of the car: "; cin >> data.make;
cout << "Enter the model of the car: "; cin >> data.model;
cout << "Enter the drive train of the car: "; cin >> data.drive_train;
cout << "Enter the color of the car: "; cin >> data.color;
cout << "Enter the amount of miles on the car: "; cin >> data.miles;

ofstream userinput (“cardatabase.dat”, ios::binary | ios::app);

userinput.write((char *)&data, sizeof(data));

else if (datatypechoice == “2”)

Cars data;
ifstream readdat (“cardatabase.dat”, ios::binary);

cout << "Cannot open file."; return 1; } *)&data, sizeof(data)); cout <<"Name:" << << endl << "Make:" << data.make << endl << "Model:" << data.model << endl << "Drive train:" << data.drive_train << endl << "Color:" << data.color << endl << "Miles:" << data.miles << endl; readdat.close(); } else { cout << " NOT AN OPTION!!!!!!!!!!!!!!1111111111111\n\n\n"; } cout << endl; return 0; } That is my code. When i run it and hit 1 it works, but when i run it again and choose 2 it segmentation faults. HELP!!! the dat file is nonexistant 'til u create it with the prog Best answer:

Answer by LoverOfWine
Since we don’t have your dat file it is difficult to see but I would highly suspect you have extra characters in your file or it isn’t matching the format of your structure. Unless you know exactly how the structure is organized in memory (especially with objects embedded in it) that is very unsafe.

Rather than read the whole structure in at one time, break it up by field and see which one is causing your problems.

Also, reading over top of a string object probably isn’t good either.

Add your own answer in the comments!

Subscribe to RSS feed

Dallas Cowboys vs. New York Jets    Watch Pittsburgh Steelers vs Baltimore Ravens live stream, NFL, week 1, 11.09.2011  Live TV Streams Discussions