为什么在C++(Visual Studio)中,control+P会导致无限循环

Why is control + P leading to infinite loop in C++ (Visual Studio)?

本文关键字:control+P 无限循环 C++ Visual Studio 为什么      更新时间:2023-10-16

我已经编程了一段时间(用Prolog、Scheme和一点C语言),但我最近决定复习一下我的C++知识。我解决了一个用来说明矢量的问题。它本质上是一个创建数据库的项目,该数据库创建一个向量来临时存储用户输入到其中的各种游戏,并删除他们不想要的游戏。代码本身运行得很好,不像scheme或Prolog那样漂亮,但它确实有效。

然而,我不小心在程序的第一个提示中键入了"Control p",我得到了最奇怪的结果:它开始了一个无限循环我用"Control Z"再次尝试,得到了相同的结果。我还没有尝试过其他关键组合,但我想可以找到其他一些。这不是一个超级令人担忧的问题,但我很好奇它为什么会这样做。它是关于C++的东西,还是仅仅是Visual Studio?不管怎样,这是来源:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout << "Welcome to the Cpp Games Database!";
int x = 0;
string game = "";
vector <string> games;
vector <string>::const_iterator iter;
while (x != 4){
    cout<< "nnPlease choose from the list bellow to decide what you want to do:n";
    cout<< "1. Add Games to the Database.n"
        << "2. Remove Games from the Database.n"
        << "3. List all the Games.n"
        << "4. Exit.n"
        << "n(Type the number of your choice and hit return)n";
    cin >> x;
    switch (x){
        case 1:
            game = "";
            do{
                cout << "nPlease Input a Game (type esc to exit): ";
                cin >> game;
                games.push_back(game);
            } while (game != "esc");
            games.pop_back();
            break;
        case 2:
            game = "";
            do{
                cout << "nPlease input the game you would like to remove(or type esc to exit): ";
                cin >> game;
                iter = find(games.begin(), games.end(), game);
                if(iter != games.end())
                    games.erase(iter);
                else cout << "nGame not found, try again please.n";
            } while (game != "esc");
            break;
        case 3:
            cout << "nYour Games are:n";
            for (iter = games.begin(); iter != games.end(); iter++)
            {
                cout << endl << *iter << endl;
            }
            break;
        default: break;
    }
}
return 0;
}

由于您没有为cin输入有效数据,因此它被困在那里,等待数据被重新处理或丢弃以进行新的输入。您需要检查您的输入,并且只接受有效的数据。从本质上讲,cin是保留它给出的原始数据,并不断尝试处理它

请始终验证您的输入,如果输入无效,请将其丢弃。

以下是关于同一问题的另一个答案,以获得更多见解(来源)。https://stackoverflow.com/a/17430697/1858323