我無法弄清楚如何做到這一點。計算數組中的匹配
的問題是:實現函數
int count_matches(const string arr[], int size, string query);
返回在數組中是等於或query
-1
串的數目,如果尺寸如果小於0
我的回答:
#include <iostream>
#include <cmath>
#include<string>
using namespace std;
int count_matches(const string arr[], int size, string query){
int i = 0;
int numMatches;
for (;i<size;i++) {
if (string[i] == (string[i]+1)){
numMatches++;
}
}
return numMatches;
}
int main(){
string selection;
const string array[4]={"dog", "cat", "dog", "dog"};
cout<<"which animal do you want?"<<endl;
cin>> selection;
cout<< "there are " << count_matches(array, 4, selection)<< " matches"<<endl;
return 0;
}
有什麼不對?
你的數組名稱是'arr',那麼'string [i]'是什麼?另外,查看'string [i] + 1'並考慮它做了什麼,因爲'int numMatches;'是未初始化的,你認爲'numMatches ++;'會做什麼?你在哪裏使用'query'? – 2012-03-30 03:22:26
你根本不使用'query'變量。我不這可能是你想要的...哦,你可能應該初始化'numMatches' ... – mcmcc 2012-03-30 03:23:42
我如何「重新初始化」numMatches? – user1145538 2012-03-30 04:05:25