我希望能夠在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