我正在編程一個控制檯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