Reputation: 1
I am programming a console C++ shopping list program and I am getting this weird looping error when I attempt to delete an item from the shopping list. If the name of the item I am trying to delete is more than one word, it loops between the main menu end of this function extremely rapidly.
The code for the deleteItem function is as follows:
void deleteItem()
{
string itemToDelete;
cout << "Which item would you like to delete?" << endl;
cin >> itemToDelete;
iFile.open("ShoppingList.dat");
if(!iFile.is_open()) //check that file exists
{
cout << "Shopping List doesn't exist! Returning to main menu." << endl;
cin.get();
mainMenu();
}
oFile.open("Transfers.dat", ios::trunc); //create and/or clear temp transfers.dat file
oFile.close();
while (!iFile.eof())
{
getline(iFile, newItem);
if(newItem.compare(itemToDelete) != 0)
{
oFile.open("Transfers.dat", ios::app);
oFile << newItem << endl;
oFile.close();
}
}
iFile.close();
int result;
remove("ShoppingList.dat"); //delete old ShoppingList.dat
result=rename("Transfers.dat", "ShoppingList.dat"); //Rename the file with transfered data to the Shoping List
cout << "Success" << endl;
cin.ignore();
cin.get();
mainMenu();
}
All necessary variables for the function have been declared and all necessary headers have been included. This is not causing any compiler flags on Code::Blocks, but it is causing this strange looping when itemToDelete
is longer than one word.
Upvotes: 0
Views: 166
Reputation: 63471
Well, the most probable solution is that you meant to do:
getline( cin, itemToDelete );
If you use cin >> itemToDelete
it will only read one word. You haven't shown any of the logic outside of deleteItem()
so it's hard to comment on what effect this will have.
However, I am curious about what the mainMenu()
function does. You seem to call it as if it's going to return from your deleteItem()
function, which of course it doesn't. Don't you mean return
?
Upvotes: 2