c++ - 为什么从 std::istream 读取记录结构字段失败,我该如何解决?

标签 c++ parsing c++11 iostream

假设我们有以下情况:

  • 一个记录结构声明如下

    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/23047052/

相关文章:

python - 使用 ctypes 将 OpenCV 图像作为函数参数传递

c++ - 非默认构造函数类型的继承构造函数 + 类内初始化失败

c++ - 向 MFC 应用程序添加非按钮超链接

java - 具有整数文字的解析器

c++ - 使用 sstream 序列化 std::map

c++ - 通过可变参数模板传递右值引用时出现编译器错误

python - 在 Python 中提取一些 HTML 标记值

regex - 为什么在线解析器似乎停止在正则表达式?

c++ - "delay"构造 C++ 对象最惯用的方法是什么?

c++ - 从复制构造函数调用构造函数