Reading data from a file and storing it into a vector

前端 未结 2 1644
滥情空心
滥情空心 2021-01-25 15:10

I\'m trying to read a list of items from from a file and then store them into a vector. The issue is my code is adding the last item to the vector twice and I\'m not sure why th

2条回答
  •  滥情空心
    2021-01-25 15:39

    This is a typical symptom of the while (!infile.fail()) anti-pattern.

    I'd define a struct and overload operator>> for that type:

    struct item { 
        std::string name;
        std::string unit;
        int amount;
        int price;
    };
    
    std::istream &std::operator>>(std::istream &is, item &i) { 
        getline(is, i.name, '-');
        getline(is, i.unit, '-');
        is >> i.amount;
        return is >> i.price;
    }
    

    With those defined, reading the data borders on trivial:

    std::ifstream inputFile("fileNameHere");
    
    std::vector items { std::istream_iterator(inputFile),
                                  std::istream_iterator() };
    

    [I changed it from list to vector, because, well, you really don't want list. You can change it back, but probably shouldn't.]

提交回复
热议问题