I'm working with vectors in c++ for the first time. In my assignment, I have to load a vector with objects I create with data from a text file. So what I am trying to do is read a line of data from a text file, create an object with that data, put the object into the vector, and then repeat. I (attempt to) do this with a function that looks like this:
Code:
int loadInventory(vector<Item>& stock, string file)
{
Item inputItem;
ifstream inFile;
int count = 0;
inFile.open(file);
inFile >> inputItem;
stock.push_back(inputItem);
while (inFile >> inputItem)
{
stock.push_back(inputItem);
count++;
}
cout << count;
inFile.close();
sort(stock.begin(), stock.end());
return 0;
}
For a reason that I'm sure is pretty simple but I just can't see, all this is doing is reading the first line of the file, creating that object, and storing it in the vector. I know that it is reading that line and creating the object because other parts of the program work correctly if I'm trying to access the data stored in that first object. For some reason, no other data is being read in. The "while(inFile >> inputItem) loop does not get entered at all and I don't see why. I used the count variable for the purpose of checking that. If I comment out the first "infile >> inputItem", then the while loop gets entered once and I still get that first line of data and nothing else.
Instead of "while(inFile >> inputItem)" I had "while(!inFile.eof()), but that was leading to an infinite loop for some reason.
I'm really at a loss here. This seems so simple and I can't understand why it isn't working, especially the way it isn't working.
BTW, the function is an int because of error handling that I got rid of to make this shorter. I know the error handling code isn't somehow the problem because I've tried it with that code removed.