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

后端 未结 9 2306
野性不改
野性不改 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:21

    When seeing such an input file, I think it is not a (new way) delimited file, but a good old fixed size fields one, like Fortran and Cobol programmers used to deal with. So I would parse it like that (note I separated forename and lastname) :

    #include 
    #include 
    #include 
    #include 
    #include 
    
    struct Person {
        unsigned int id;
        std::string forename;
        std::string lastname;
        uint8_t age;
        // ...
    };
    
    int main() {
        std::istream& ifs = std::ifstream("file.txt");
        std::vector persons;
        std::string line;
        int fieldsize[] = {8, 9, 9, 4};
    
        while(std::getline(ifs, line)) {
            Person person;
            int field = 0, start=0, last;
            std::stringstream fieldtxt;
            fieldtxt.str(line.substr(start, fieldsize[0]));
            fieldtxt >> person.id;
            start += fieldsize[0];
            person.forename=line.substr(start, fieldsize[1]);
            last = person.forename.find_last_not_of(' ') + 1;
            person.forename.erase(last);
            start += fieldsize[1];
            person.lastname=line.substr(start, fieldsize[2]);
            last = person.lastname.find_last_not_of(' ') + 1;
            person.lastname.erase(last);
            start += fieldsize[2];
            std::string a = line.substr(start, fieldsize[3]);
            fieldtxt.str(line.substr(start, fieldsize[3]));
            fieldtxt >> age;
            person.age = person.age;
            persons.push_back(person);
        }
        return 0;
    }
    

提交回复
热议问题