假设我们有以下情况:
struct Person {
unsigned int id;
std::string name;
uint8_t age;
// ...
};
Run Code Online (Sandbox Code Playgroud)
ID Forename Lastname Age
------------------------------
1267867 John Smith 32
67545 Jane Doe 36
8677453 Gwyneth Miller 56
75543 J. Ross Unusual 23
...
Run Code Online (Sandbox Code Playgroud)
应该读入该文件以收集上述任意数量的Person记录:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题:(这是一个常见问题,以一种或另一种形式)
我可以做些什么来读取将它们的值存储到一个actRecord变量字段中的单独值?
上面的代码示例最终出现运行时错误:
Runtime error …Run Code Online (Sandbox Code Playgroud)