Reputation: 39
I want my program to be able to remember where it left off in a .txt
file in order to proceed to the next input upon reiteration through a loop.
For instance, a text file containing:
Apples
Bananas
Oranges
would be accessed through a function GetItem()
that appends the next file input into a vector of items. How do I make the function add Apples
the first time, Bananas
the second time, and Oranges
the third iteration? As of now, each call to GetItem()
keeps adding the first element to the vector, giving a vector containing:
Apples
Apples
Apples
Because the file keeps opening from the beginning. Any help would be appreciated.
This is a simplified version of lengthy amounts of code that I could include, but would distract from the main purpose of the question. If the code is needed, I would be happy to include it.
vector<Item*> AddItemToInventory(vector<Item*> inventory) {
if (inptLctn == 'f') {
inptFile.open("TestFood.txt");
if (!inptFile.is_open()) {
cout << "Could not open file." << endl;
exit(1);
}
inptFile >> usrInptName;
inptFile >> usrInptQnty;
inptFile >> usrInptExpr;
inptFile >> usrInptPrice;
}
prdc = new Produce;
prdc->SetName(usrInptName);
prdc->SetQuantity(usrInptQnty);
prdc->SetExpiration(usrInptExpr);
prdc->SetPrice(usrInptPrice);
inventory.push_back(prdc);
return inventory;
}
Upvotes: -3
Views: 111
Reputation: 73
Open the file before you use it and close it after you are done using it. The problem is that you are continually closing the input file so when you re-open it, it starts at the beginning again.
You should only open and close your input file once.
Upvotes: 3