std::字符串类查找函数不返回预期结果.我可能用错了

std::string class find function not returning expected results. I may be using it incorrectly

本文关键字:结果 错了 返回 字符串 查找 函数 std      更新时间:2023-10-16

使用字符串类的 find 方法,我在查询中没有得到正确的结果。这是我的代码

int main()
{
    string phoneData;
    string name;
    string phoneNumbers[51];
    ifstream inputFile;
    inputFile.open("phonebook");
    int i = 0;
    while (getline(inputFile, phoneData))
    {
        phoneNumbers[i] = phoneData;
        i++;
    }
    cout << "Enter a name or partial name to search for: ";
    getline(cin, name);
    cout << endl << "Here are the results of the search: " << endl;
    for(int i =0;i<50;i++)
    {
        if (name.find(phoneNumbers[i]) == 0)
            cout << phoneNumbers[i] << endl;
    }
    inputFile.close();
    return 0;
}

你没有正确使用它。 string::find() 在找到匹配项时返回起始位置,如果未找到匹配项,则返回 string::npos。 您还可以向后搜索。 您正在"电话号码[i]"中查找"名称",而不是相反。 循环内的检查应如下所示:

if (phoneNumbers[i].find(name) != string::npos)
    cout << phoneNumbers[i] << endl;

更改

if (name.find(phoneNumbers[i]) == 0)

if (phoneNumbers[i].find(name) != std::string::npos)

前者试图在名称中查找电话号码[i]。 第二个(我相信是你的意图)是在电话号码[i]中搜索名称。其次,std::string::find的故障回报std::string::npos不为零。