gpt4 book ai didi

c++ - 使用 For 循环显示 1 个结果

转载 作者:行者123 更新时间:2023-11-30 01:44:10 25 4
gpt4 key购买 nike

这是我的代码:

void IDsearch(vector<Weatherdata>temp)
{
int userinput;
cout << "Enter the ID of the Event and i will show you all other information: " << endl;
cin >> userinput;
for(unsigned int i = 0; i < temp.size();i++)
{
if(userinput == temp[i].eventID)
{
cout << "Location: " << temp[i].location << endl;
cout << "Begin Date: " << temp[i].begindate << endl;
cout << "Begin Time: " << temp[i].begintime << endl;
cout << "Event Type: " << temp[i].type << endl;
cout << "Death: " << temp[i].death << endl;
cout << "Injury: " << temp[i].injury << endl;
cout << "Property Damage: " << temp[i].damage << endl;
cout << "Latitude: " << temp[i].beginlat << endl;
cout << "Longitude: " << temp[i].beginlon << endl;
}
}
}

我想做的是在遍历所有值后生成它,如果 userinput 与其中任何一个都不匹配,则只打印一次“它不匹配”。我知道如果我使用 else 或 if(userinput != temp[i].eventID) 它只会多次显示“它不匹配”。我是 C++ 的新手,请帮忙。谢谢

最佳答案

您可以使用标志来记住是否找到了某些元素。

void IDsearch(const vector<Weatherdata>&temp) // use reference for better performance
{
int userinput;
bool found = false;
cout << "Enter the ID of the Event and i will show you all other information: " << endl;
cin >> userinput;
for(unsigned int i = 0; i < temp.size();i++)
{
if(userinput == temp[i].eventID)
{
cout << "Location: " << temp[i].location << endl;
cout << "Begin Date: " << temp[i].begindate << endl;
cout << "Begin Time: " << temp[i].begintime << endl;
cout << "Event Type: " << temp[i].type << endl;
cout << "Death: " << temp[i].death << endl;
cout << "Injury: " << temp[i].injury << endl;
cout << "Property Damage: " << temp[i].damage << endl;
cout << "Latitude: " << temp[i].beginlat << endl;
cout << "Longitude: " << temp[i].beginlon << endl;
found = true;
}
}
if(!found)
{
cout << "it doesnt match" << endl;
}
}

关于c++ - 使用 For 循环显示 1 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36624496/

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