so teacher gave solutions lab had couple of weeks ago, , differs using when submitted assignment. popped code address book program, nothing prints out, , wondering if knew how print out screen main. have tried few things, best can 1 entry print out , nothing else. heres code given:
void addressbook::showall2(string fname) { person p; people2 tp; ifstream indata(fname.c_str(), ios::in); if(indata.fail()) throw addressbookexception("cannot open file read "); people.clear(); int = 0; while(!indata.eof()) { indata.seekg(i * sizeof(people2)); indata.read(reinterpret_cast<char *>(&tp), sizeof(people2)); p.fname = tp.fname2; p.lname = tp.lname2; p.address = tp.address2; people.push_back(p); i++; } indata.close(); return; }
the thing have changed throw exception, (our current project). used bool function, return true or false. not given code form main beacuse isn't concerned part, ever it. i'm wondering if knows how print out screen. i've tried changing this:
void addressbook::showall2(string fname, string &str) { person p; people2 tp; ifstream indata(fname.c_str(), ios::in); if(indata.fail()) throw addressbookexception("cannot open file read "); people.clear(); int = 0; while(!indata.eof()) { indata.seekg(i * sizeof(people2)); indata.read(reinterpret_cast<char *>(&tp), sizeof(people2)); p.fname = tp.fname2; p.lname = tp.lname2; p.address = tp.address2; people.push_back(p); i++; indata >> str; } indata.close(); return; }
and in main have this:
void printfile() //prints stored file info screen { string str; addressbook *newbook = addressbook::newbookinst(); menu *m = menu::menuinst(); try { newbook->showall2("addressbook", str); cout << str << '/n' << endl; } catch(exception e) { cerr << e.what(); } m->waitkey(); }
so care show me missing? assignment done, feel free explain in detail if you'd like, or post code , can figure out. i'm going little crazy trying understand how print code. (my version worked fine btw, doesn't of this.) thanks
your professors code wrong because tests eof in wrong place, needless seekg, i'd worried professor writing bad code.
while(!indata.eof()) { indata.seekg(i * sizeof(people2)); indata.read(reinterpret_cast<char *>(&tp), sizeof(people2)); ... }
should written this
for (;;) { indata.read(reinterpret_cast<char *>(&tp), sizeof(people2)); if (indate.eof()) break; ... }
you should test eof after read not before. it's common mistake among newbies, it's not mistake professor should making. secondly there's no need seekg, since going through file beginning end. it's not bug, it's not necessary.
indata.close
unnecessary because ifstream destructor close file you.
answer question this
indata.read(reinterpret_cast<char *>(&tp), sizeof(people2)); p.fname = tp.fname2; p.lname = tp.lname2; p.address = tp.address2; cout << p.fname << ' ' << p.lname << ' ' << paddress << '\n';
try code professor's version of loop , you'll see why it's bugged.
Comments
Post a Comment