gpt4 book ai didi

c++ - 控制台 C++ 中的循环错误

转载 作者:行者123 更新时间:2023-11-28 03:33:11 28 4
gpt4 key购买 nike

我正在编写一个控制台 C++ 购物 list 程序,当我试图从购物 list 中删除一个项目时,我遇到了这个奇怪的循环错误。如果我要删除的项目的名称超过一个单词,它会非常快速地在该功能的主菜单结束之间循环。

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 长于一个单词时导致这种奇怪的循环。

最佳答案

嗯,最可能的解决方案是你打算做的:

getline( cin, itemToDelete );

如果您使用 cin >> itemToDelete,它只会读取一个单词。您没有显示 deleteItem() 之外的任何逻辑,因此很难评论这会产生什么影响。

但是,我很好奇 mainMenu() 函数的作用。您似乎将其称为要从您的 deleteItem() 函数返回,当然它不会。你不是说 return 吗?

关于c++ - 控制台 C++ 中的循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11963492/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com