我正在编程一个控制台C++购物清单程序,当我试图从购物清单中删除一个项目时,出现这个奇怪的循环错误。如果我试图删除的项目名称不止一个单词,它会非常快速地在此功能的主菜单结尾之间循环。控制台C++中的循环错误
的deleteItem函数的代码如下:
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();
}
该函数所有必需的变量已被定义和所有必要的头已经被包括在内。这不会导致Code :: Blocks上的任何编译器标志,但当itemToDelete
长于一个单词时,会导致此奇怪循环。
'cin'读取直到空白。如果你想要多个单词,使用'getline'。 – chris 2012-08-15 02:53:16