Friday, 15 March 2013

c++ - Reading data from a file and storing it into a vector -


I am trying to read a list of items from a file and then store them in vector. The point is that my code is adding the last item to the vector twice and I'm not sure why it keeps reading the file, even if the program has reached the end.

What's in the text file here when I display the contents of the vector, then the "orange" row appears twice I

apple-pound -102

Orange-Pound-5 6

Here is the code // Read the contents of a file list

  while (! InputFile.fail ()) {// Remove the line from the list getline (inputFile, item_name, '-'); Getline (inputfile, item_unit, '-'); Input File & gt; & Gt; Item_amount; Input File & gt; & Gt; Price of goods; // Create an example of item object item new_itimate (item_name, item_uites, item_mount, item_pres); // Push the list vector list. Push_back (New_Item); } // close the file inputFile.close ();  

The problem is that the "unsuccessful" flag is not set unless you try Do not do anything on the data reading from the file. Here's a quick way to decide:

(;;) {// Get the line from the match (inputfile, item_name, '-'); Getline (inputfile, item_unit, '-'); Input File & gt; & Gt; Item_amount; Input File & gt; & Gt; Price of goods; Break if (inputFile.fail ()); // Create an example of item object item new_itimate (item_name, item_uites, item_mount, item_pres); // Push the list vector list. Push_back (New_Item); }

If this is for a learning exercise, and you have & gt; & Gt; the operator has not yet learned, then it should do it. Otherwise, operator & gt; & Gt; The approach is better.


No comments:

Post a Comment