C++ cin >> 不再开始

C++ cin >> not starting again

好的,所以我正在为一本 C++ 编程书做练习,它要求我编写一个程序,在这些名称旁边输入名称和分数,它们都保存在向量中。然后,当我输入完这些后,它会提示我输入一个名字,然后它会找到这个名字对应的分数。 e.x。我输入 "John" 它 returns 5 如果这是我把约翰的分数作为。

我遇到的问题是,在用户输入完姓名和分数后,我的程序提示用户输入姓名(以找到相应的分数),代码只是跳过 cin 命令并继续,使我的程序无法运行。我将 post 完整的程序,然后是我需要帮助的部分:

#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) 不接受新值的原因吗?感谢您的帮助。

CTRL+Z 被解释为文件结束标记。一旦 cin 看到该标记,它就会进入错误状态(cin.eof()cin.fail() 将是 true,这意味着 (bool)cin 将是 false ,这就是你的第一个循环停止的原因)。处于错误状态时,cin 将不再接受任何输入。

要让 cin 恢复到良好状态,您可以调用 cin.clear()。一旦恢复到良好状态,它将再次接受输入。