std::字符串类查找函数不返回预期结果.我可能用错了
std::string class find function not returning expected results. I may be using it incorrectly
使用字符串类的 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
不为零。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- 首要问题的答案让值班员搞错了
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 如何正确使用 >=?(a+f()+c)>=0 错了吗?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 没有输出的合并排序我做错了什么?
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 在C++中使用 AKS 素数测试计算双胞胎素数 我做错了什么?
- 指针相关的UE4崩溃.我的指针哪里错了?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- FFMPEG,C++,内存泄漏,我做错了什么?
- 我做错了什么?反向字符串 C++
- 我在这个课上做错了什么?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- std::字符串类查找函数不返回预期结果.我可能用错了
- Rcpp犰狳fastlm结果与R的lm不同,我做错了什么?