gpt4 book ai didi

C++ 字符串数组搜索每个项目的输出

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:37 25 4
gpt4 key购买 nike

我知道这个问题的标题有点令人困惑,但我真的需要帮助。我需要在包含许多字符串的数组中找到一个字符串。如果未找到该字符串,则会显示相应的消息。然而,当我使用 for 循环时,它会为数组中的每个未找到的字符串显示此消息,尽管它也显示找到的字符串......我希望你明白我的意思,如果我没有意义,我很抱歉。这是我的代码:

void Store::search() {
string name;
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);

for (int i = 0; i < quantity; i++) {
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
}
else
{
cout << "Product doesn't exist in database!" << endl;
}
}

}

该代码适用于搜索,但如何停止输出“数据库中不存在产品!”对于数组中未找到的每个项目(即使找到搜索项目)?

提前谢谢你

最佳答案

您可以使用语句标志:

void Store::search() 
{
string name;
bool found = false
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);

for (int i = 0; i < quantity; i++)
{
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true;
break;
}

if (!found)
cout << "Product doesn't exist in database!" << endl;

}

关于C++ 字符串数组搜索每个项目的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46280855/

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