Why does reading a record struct fields from std::istream fail, and how can I fix it?

后端 未结 9 2122
野性不改
野性不改 2020-11-21 11:40

Suppose we have the following situation:

  • A record struct is declared as follows

struct Person {
    unsigned int id;
    std::st         


        
9条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 12:13

    One viable solution is to reorder input fields (if this is possible)

    ID      Age Forename Lastname
    1267867 32  John     Smith    
    67545   36  Jane     Doe      
    8677453 56  Gwyneth  Miller   
    75543   23  J. Ross  Unusual  
    ...
    

    and read in the records as follows

    #include 
    #include 
    
    struct Person {
        unsigned int id;
        std::string name;
        uint8_t age;
        // ...
    };
    
    int main() {
        std::istream& ifs = std::cin; // Open file alternatively
        std::vector 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;
    }
    

提交回复
热议问题