Reputation: 674
Suppose I have a struct with five data members:
struct Info {
std::string name;
std::string last_name;
std::string school;
int age;
int dob;
}
And a string in the format: Joe Bob University 18 050797 where each field represents something I want to read into each member of the struct. I want to know for sure, that each data member in the struct was read in a value, and that the read did not fail. Is there an elegant way of accomplishing this?
void fill_info(const std::string &line, Info *fields) {
istringstream ss(line);
ss >> fields->name;
ss >> fields->last_name;
ss >> fields->school;
ss >> fields->age;
ss >> fields->dob;
}
Upvotes: 0
Views: 300
Reputation: 56547
You can perform the insertion in one line and test the stream
if(!(ss >> fields->name >> fields->last_name >>\
fields->school >> fields->age >> fields->dob))
std::cout << "error reading the data";
If you want to see exactly which field failed, you can test each individual insertion. Then, you can validate the input.
Upvotes: 2