2017-05-03 32 views
-1

我需要添加一個函數來在字符串數組中搜索並調出帶有關聯電話號碼的用戶。雖然我輸了。任何創建的功能只會顯示沒有號碼的人員姓名。如果沒有找到,它需要說錯誤。如何向數組添加搜索功能?

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; 
} 
+3

而不是有平行數組,你真的應該考慮使用類/結構來將電話號碼和名字綁定在一起。然後您可以擁有這些記錄的單個數組。使這件事更容易處理。 – NathanOliver

+2

什麼思考過程導致決定以這種方式格式化您的代碼? –

+0

如果用戶輸入的電話號碼數量大於100,該數組將會溢出,導致未定義的行爲。 – diametralpitch

回答

-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; 
} 

當然,這是非常基本的,你可以讓它變得更好,希望它有幫助!

+0

謝謝Emanuele,這是我需要的。我仍然在學習,我的老師提供的例子很糟糕。 – ModdedDragon

+0

如果您有任何問題可隨時提出其他問題,請不要有任何問題 – Emanuele

+0

無緣無故降低投票率。 – Emanuele