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

相关文章:

c++ 17 filesystem::remove_all 带通配符路径

javascript - PHP从xml文件中解析json

c++ - 如何忽略无序映射/映射中的单个字符串值?

c++ - 在 std::map 中使用 std::less 无法编译

c++ - Unix如何通过两种方式进行管道通信

c++ - 在 C++ 中使用 std::vector 的性能损失是什么?

java - 具有低 GC 负载的快速 CSV 解析器

java - JJT 文件中的韩文字符集

c++ - 这个 lambda 捕获问题是 gcc 编译器错误吗?

c++ - 如果跨线程共享变量,将变量标记为 volatile 有用吗?