istream - Handling exception std::out_of_range c++ -
i trying read flight schedules file flight class.
i experienced problemn when using microsoft visual studio 2015. tried same code on tutorialspoint c++ online compiler , works fine.
here example data of text file:
las vegas; 21:15; aa223; a3; dallas; 21:00; ba036; a3; london; 20:30; aa220; b4; mexico; 19:00; vi303; b4; london; 17:45; ba087; b4; here error message receive:
unhandled exception @ 0x75f25b68 in sf.exe: microsoft c++ exception: std::out_of_range @ memory location 0x00c5ee9c.
and here stream extractor in problem apparently occurs
istream &operator>>(istream &is, flight &f) { std::string singleline; >> singleline; std::string s0, s1, s2, s3; size_t loc = singleline.find(';'); s0 = singleline.substr(0, loc); singleline.erase(0, loc + 1); loc = singleline.find(';'); s1 = singleline.substr(1, loc - 1); singleline.erase(0, loc + 1); loc = singleline.find(';'); s2 = singleline.substr(1, loc - 1); singleline.erase(0, loc + 1); s3 = singleline.substr(1, 2); f.set_lightno(s0); f.set_destination(s1); f.set_departure(s2); f.set_gateno(s3); return is; }
the problem read lines with:
is >> singleline; // <== ouch ! the singleline end @ first whitespace encountered , not hold full line !
in example data, first whitespace after first ;. when second find(';'), return value not found, i.e. string::npos, maximum loc can contain ( avery big number). when try access substr(1, loc - 1) you're definitively out of range.
it should work if replace line with:
getline (is, singleline); // full line until nweline or eof suggestion:
a further improvement check read successful before else:
istream &operator>>(istream &is, flight &f) { std::string singleline; if (getline (is, singleline)) { ... } return is; }
Comments
Post a Comment