Reading data from a file and storing it into a vector

前端 未结 2 1681
滥情空心
滥情空心 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: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.

提交回复
热议问题