对于我正在编写的程序,我需要在字符串数组中找到特定单词的位置,但我不知道如何做。这是我编写的代码,但它不起作用:
int location;
string input;
cout << "Type your name" << endl;
cin >> input;
for (int i = 0; i <= count; i++)
{
call_DB[i].name;
if (call_DB[i].name == input)
{
location = i;
}
}
该代码有什么问题,我该如何解决?谢谢。
最佳答案
试试 std::find_if
,它在数组中搜索满足提供的预测函数的项目。
auto iter = std::find_if(call_DB, call_DB + count, [&input](const YOUR_CALL_DB_TYPE& item ){ return item.name == input; });
if(iter == call_DB + count)
printf("Not found\n");
else
printf("Found: %s\n", iter->name.c_str());
如果找到这样的项目,索引是到数组基址的距离,size_t index = iter - call_DB;
关于c++ - 如何在 C++ 中的字符串数组中查找单词位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42942100/