我希望能够在C++中搜索字符串数组。我有这样的数据:如何在C++中搜索字符串数组
"Foo Becky, 924-334-2514",
"Becky Warren, 555-1223",
"Geri Palmer, 555-8787",
"Ron Palmer, 555-2783"
如果用户键入Bec
,程序找到名称Foo Becky, 924-234-2314
。如果用户键入Palmer
,则程序应该显示Geri Palmer, 555-8787
和Ron Palmer, 555-2783
这是我到目前为止有:
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
string search;
while(1){
cout << "How many data you want to input: "<< endl;
cin >> n;
cin.ignore(1000, 10);
if(n > 0 && n < 20){
break;
}
cout << "Number of data can not be negative or more than 20. "<< endl;
}
string* data = new string[n];
for(int i=0; i< n; i++){
cout << "Enter [First Name] [Last Name], [Phone-Number] and then hit "
<< "enter." << endl << "e.g: Foo Becky, 925-245-413"<< endl;
getline(cin,data[i]);
cout << endl;
}
cout << "Enter what you want to search for: "<< endl;
getline(cin, search);
for(int i =0; i< n; i++){
if(search == data[i]){
cout << data[i]<< endl;
}
}
delete [] data;
return 0;
}
如何搜索在C++字符串数组?
那么你的问题到底是什么?你有你的代码和任务,但没有问题。 – taocp 2013-03-25 02:35:07
我会回应@SongWang说的,但我会根据你的代码推断你的问题。你的基本逻辑或多或少都是正确的,但使用'=='将不起作用。您可能想了解['std :: string :: find'](http://www.cplusplus.com/reference/string/string/find/) – 2013-03-25 02:36:14
我很抱歉,我没有清楚地问。所以我的问题是,如何让程序搜索用户想要在之前填充的数组中搜索的内容。但是,尽管用户只搜索“Palmer”,但该程序必须同时显示“Geri Palmer,555-8787”和“Ron Palmer,555-2783” – dodgerblue 2013-03-25 03:12:48