Reading data from a file and storing it into a vector

前端 未结 2 1643
滥情空心
滥情空心 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<New_Item> items { std::istream_iterator<Item>(inputFile),
                                  std::istream_iterator<Item>() };
    

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

    0 讨论(0)
  • 2021-01-25 15:49

    The problem is that the "fail" flag is not set until you make an attempt at reading some more data from the file. Here is a quick way of fixing this:

    for (;;) {
        //Extract the line from the list
        getline(inputFile,item_name,'-');
        getline(inputFile,item_unit,'-');
        inputFile >> item_amount;
        inputFile >> item_price;
        if (inputFile.fail()) break;
        //Create an instance of the item object
        Item New_Item(item_name, item_unit, item_amount,item_price);
        //Push it to the list vector
        list.push_back(New_Item);
    }
    

    If this is for a learning exercise, and you have not learn the >> operator yet, this should do it. Otherwise, the operator>> approach is better.

    0 讨论(0)
提交回复
热议问题