2017-05-03 1 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

관련 문제