【发布时间】:2016-03-26 05:35:39
【问题描述】:
好的,所以我正在为一本 C++ 编程书籍做一个练习,它要求我编写一个程序,在这些名称旁边输入名称和分数,它们都保存在向量中。然后,在我输入完之后,它会提示我输入一个名字,然后它会找到那个名字对应的分数。前任。如果我输入 John 的分数,我输入“John”它返回 5。
我遇到的问题是,在用户输入完名称和分数后,我的程序提示用户输入名称(以查找相应的分数),代码只是跳过了cin 命令继续前进,使我的程序无法正常工作。我将发布完整的程序,然后是我需要帮助的部分:
#include "std_lib_facilities.h"
int main()
{
vector<string>names;
vector<int>scores;
string name = "";
int score;
while(cin >> name && cin >> score)
{
for(int i = 0; i < names.size(); ++i) // checks all previous words
{
if(name == names[i]) // if the name is used twice, exit
{
cout << "Error. Terminating...\n";
exit(4);
}
else;
}
names.push_back(name);
scores.push_back(score);
}
cout << "Enter a name, which I will find the score for. \n";
string locateName;
while(cin >> locateName) // i think the program won't accept the locateName
{
for(int i = 0; i < names.size(); ++i)
{
if(locateName == names[i])
{
cout << names[i] << "'s score is " << scores[i] << '\n';
}
else { cout << "Name not found. \n"; }
}
}
return 0;
}
这是不工作的部分:
cout << "Enter a name, which I will find the score for. \n";
string locateName;
while(cin >> locateName)
{
for(int i = 0; i < names.size(); ++i)
{
if(locateName == names[i])
{
cout << names[i] << "'s score is " << scores[i] << '\n';
}
else { cout << "Name not found. \n"; }
}
}
具体来说,while(cin >> locateName)。以下是一些附加信息:每当我输入姓名时 (John 5 Bob 6 Pete 9),我按 CTRL + Z 然后按 ENTER 停止 cin。然后程序就结束了。这是(ctrlZ)导致while(cin >> locateName) 不接受新值的原因吗?感谢您的帮助。
【问题讨论】:
-
这里有一个提示/想法 - 它说了多少次“未找到名称”?一次,还是两次? (我问这个是因为当你在循环中搜索时,对于循环中的每个元素,你都会输出一些东西。在你的例子中,如果你寻找 Pete,你会得到:“找不到名字。\n找不到名字. \nPete 的分数是 9\n")
-
离题建议:不要将名称和分数分成两个向量,创建一个存储两者的结构,并创建该结构的单个向量。
-
@user4581301 这本书的练习说要使用向量。我们还没有学过结构。
-
@ScottMermelstein 现在它甚至没有说“找不到名称”。它只是结束程序。