我需要添加一個函數來在字符串數組中搜索並調出帶有關聯電話號碼的用戶。雖然我輸了。任何創建的功能只會顯示沒有號碼的人員姓名。如果沒有找到,它需要說錯誤。如何向數組添加搜索功能?
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;
}
而不是有平行數組,你真的應該考慮使用類/結構來將電話號碼和名字綁定在一起。然後您可以擁有這些記錄的單個數組。使這件事更容易處理。 – NathanOliver
什麼思考過程導致決定以這種方式格式化您的代碼? –
如果用戶輸入的電話號碼數量大於100,該數組將會溢出,導致未定義的行爲。 – diametralpitch