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

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

    Since we can easily split a line on whitespace and we know that the only value that can be separated is the name, a possible solution is to use a deque for each line containing the whitespace separated elements of the line. The id and the age can easily be retrieved from the deque and the remaining elements can be concatenated to retrieve the name:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    struct Person {
        unsigned int id;
        std::string name;
        uint8_t age;
    };
    

    int main(int argc, char* argv[]) {
    
        std::ifstream ifs("SampleInput.txt");
        std::vector records;
    
        std::string line;
        while (std::getline(ifs,line)) {
    
            std::istringstream ss(line);
    
            std::deque info(std::istream_iterator(ss), {});
    
            Person record;
            record.id = std::stoi(info.front()); info.pop_front();
            record.age = std::stoi(info.back()); info.pop_back();
    
            std::ostringstream name;
            std::copy
                ( info.begin()
                , info.end()
                , std::ostream_iterator(name," "));
            record.name = name.str(); record.name.pop_back();
    
            records.push_back(std::move(record));
        }
    
        for (auto& record : records) {
            std::cout << record.id << " " << record.name << " " 
                      << static_cast(record.age) << std::endl;
        }
    
        return 0;
    }
    

提交回复
热议问题