c++ - Why does reading a record struct fields from std::istream fail, and how can I fix it? -
suppose have following situation:
- a record struct declared follows
struct person { unsigned int id; std::string name; uint8_t age; // ... };
- records stored in file using following format:
id forename lastname age ------------------------------ 1267867 john smith 32 67545 jane doe 36 8677453 gwyneth miller 56 75543 j. ross unusual 23 ...
the file should read in collect arbitrary number of person
records mentioned above:
std::istream& ifs = std::ifstream("sampleinput.txt"); std::vector<person> persons; person actrecord; while(ifs >> actrecord.id >> actrecord.name >> actrecord.age) { persons.push_back(actrecord); } if(!ifs) { std::err << "input format error!" << std::endl; }
question: (that's asked question, in 1 or other form)
can read in separate values storing values 1 actrecord
variables' fields?
the above code sample ends run time errors:
runtime error time: 0 memory: 3476 signal:-1 stderr: input format error!
one viable solution reorder input fields (if possible)
id age forename lastname 1267867 32 john smith 67545 36 jane doe 8677453 56 gwyneth miller 75543 23 j. ross unusual ...
and read in records follows
#include <iostream> #include <vector> struct person { unsigned int id; std::string name; uint8_t age; // ... }; int main() { std::istream& ifs = std::cin; // open file alternatively std::vector<person> persons; person actrecord; unsigned int age; while(ifs >> actrecord.id >> age && std::getline(ifs, actrecord.name)) { actrecord.age = uint8_t(age); persons.push_back(actrecord); } return 0; }
Comments
Post a Comment