假设我们有以下情况:
记录结构声明如下
struct Person { unsigned int id; std::string name; uint8_t age; // ... };
记录使用以下格式存储在文件中:
ID Forename Lastname Age ------------------------------ 1267867 John Smith 32 67545 Jane Doe 36 8677453 Gwyneth Miller 56 75543 J. Ross Unusual 23 ...
应该读入文件以收集任意数量的上述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;
}
问题:
我可以做些什么来读取单独的值,将它们的值存储到一个 actRecord
变量的字段中?
以上code sample以运行时错误结束:
Runtime error time: 0 memory: 3476 signal:-1
stderr: Input format error!
最佳答案
一个viable solution是重新排序输入字段(如果可能的话)
ID Age Forename Lastname
1267867 32 John Smith
67545 36 Jane Doe
8677453 56 Gwyneth Miller
75543 23 J. Ross Unusual
...
读入记录如下
#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;
}
关于c++ - 为什么从 std::istream 读取记录结构字段失败,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44147452/