根据姓名和电话号码,组装一个电话簿,将朋友的姓名映射到各自的电话号码。然后,您将获得一个未知数量的名称来查询您的电话簿。对于查询的每个名称,在“name = phoneNumber”形式的新行中打印电话簿中的相关条目;如果找不到名称条目,请改为打印“未找到”。
输入格式:...
在电话簿条目行之后,存在未知数量的查询行。每行(查询)包含一个要查找的内容,和
您必须继续读取行,直到没有更多输入。
我应该如何循环直到没有更多的输入?
也有人可以告诉我这在C ++中是如何实现的吗?
这是我在Python 3中的代码:
n = int(input())
names = {}
for foo in range(n):
entry = input().split(' ')
names[entry[0]] = entry[1]
while (1==1):
check = input()
if(names.get(check)!=None):
print(check + '=' + names.get(check))
else:
print('Not Found')
这是C ++代码:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main(void)
{
map<string, string> phonebook;
int n;
cin >> n;
string key, num;
for(int i = 0; i < n; i++)
{
cin >> key >> num;
phonebook.insert(pair<string, string>(key, num));
}
while (1 == 1)
{
cin >> key;
if(phonebook.count(key) > 0)
cout << key << "=" << phonebook[key] << endl;
else
cout << "Not found" << endl;
}
}
我应该如何循环直到没有更多的输入?
您使用while循环是合适的。要捕获并消除错误,可以使用try-except
块:
n = int(input())
names = {}
for foo in range(n):
entry = input().split(' ')
names[entry[0]] = entry[1]
while True: # (1 == 1) == True
try:
check = input()
except EOFError: # catch the error
break # exit the loop
if(names.get(check)!=None):
print(check + '=' + names.get(check))
else:
print('Not Found')
也有人可以告诉我这在C ++中是如何实现的吗?
嗯......奇怪的要求。我会指向std::getline
和std::map
并让他们进行交谈。 :-)
这是正确的C ++代码:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main(void)
{
map<string, string> phonebook;
int n;
cin >> n;
string key, num;
for(int i = 0; i < n; i++)
{
cin >> key >> num;
phonebook.insert(pair<string, string>(key, num));
}
getline(cin, key);
while(getline(cin, key)) //Loop runs while we are getting input.
{
if(phonebook.count(key) > 0)
cout << key << "=" << phonebook[key] << endl;
else
cout << "Not found" << endl;
}
}