我需要添加一个函数来搜索字符串数组并调出具有相关电话号码的用户。虽然我输了。创建的任何功能仅显示没有编号的人员姓名。如果没有找到,则需要说错误。
int main(int argc, char** argv)
{
int i, n, j;
string name[100];
string phone[100];
int index[100];
cout << "How many names and phone numbers do you want to enter? " << endl
<< "Entering 0 ends the program." << endl;
cin >> n;
if (n == 0)
return 0;
for (i = 0; i < n; i++) {
cout << "Please enter a name: ";
cin >> name[i];
cout << "Please enter a phone number: ";
cin >> phone[i];
}
for (i = 0; i < n; i++) {
index[i] = i;
}
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
int temp;
if (phone[index[i]] > phone[index[j]]) {
temp = index[i];
index[i] = index[j];
index[j] = temp;
}
}
}
cout << "These entries are in ascending order by phone number: " << endl;
cout << "Name"
<< " "
<< "Phone Number" << endl;
for (i = 0; i < n; i++) {
cout << name[index[i]] << " " << phone[index[i]] << endl;
}
return 0;
}
答案 0 :(得分:-1)
此代码应该适合您(如果我理解了这个问题)
int search(string name[], string searchedName){
for(int i=0; i<100; i++){
if(searchedName == name[i])
return i; //Returns the position of the person, which is also the index of his phone number
}
return -1; //If -1 is returned it means there is no such name an "searchedName" in the vector
}
您可以像这样调用此函数
int main(){
/* all the stuff you already have inside here */
string nameToSearch;
cout<<"Insert the name of the person you want to see the number of"<<endl;
cin>>nameToSearch;
int position = search(name, nameToSearch);
if(position == -1)
cout<<"Sorry, "<<nameToSearch<<" is not in our list"<<endl;
else
cout<<"The phone number of "<<nameToSearch<<" is "<<phone[position]<<endl;
return 0;
}
当然这是非常基本的,你可以让它变得更好,希望它有所帮助!