Expand your program from either (2) or (3) above so that you can enter a particular name and then display the phone number belonging to that name. Remember that someone may enter a name that is not in the list. In this case, display a suitable message. 用c++
时间: 2023-11-28 15:50:46 浏览: 22
以下是用 C++ 编写的程序,可以实现输入姓名并显示该姓名对应的电话号码:
```c++
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
map<string, string> phone_book; // 使用 map 存储电话簿信息
phone_book["Alice"] = "1234567890";
phone_book["Bob"] = "2345678901";
phone_book["Charlie"] = "3456789012";
string name;
cout << "Enter a name to search for: ";
cin >> name;
if (phone_book.count(name)) { // 如果找到了该姓名
cout << name << "'s phone number is " << phone_book[name] << endl;
} else { // 如果未找到该姓名
cout << "Sorry, " << name << " is not in the phone book." << endl;
}
return 0;
}
```
以上代码中,我们使用 `map` 数据结构来存储电话簿信息。每个联系人的姓名作为 key,电话号码作为 value。当用户输入要查询的姓名时,我们可以使用 `count()` 函数来判断该姓名是否在电话簿中出现过,并输出相应的电话号码或未找到的提示信息。