πάν*_*ῥεῖ 19 c++ parsing iostream c++11
假设我们有以下情况:
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 time: 0 memory: 3476 signal:-1
stderr: Input format error!
Run Code Online (Sandbox Code Playgroud)
名字和姓氏之间有空格。将您的班级更改为将名字和姓氏作为单独的字符串,它应该可以工作。您可以做的另一件事是读入两个单独的变量,例如name1和name2并将其分配为
actRecord.name = name1 + " " + name2;
Run Code Online (Sandbox Code Playgroud)