【问题标题】:Why is control + P leading to infinite loop in C++ (Visual Studio)?为什么 control + P 会导致 C++(Visual Studio)中的无限循环?
【发布时间】:2014-10-31 03:04:06
【问题描述】:

我已经编程了一段时间(在 Prolog、Scheme 和一点点 C 中),但我最近决定复习我的 C++ 知识。我解决了一个旨在说明矢量的问题。它本质上是一个创建数据库的项目,该数据库创建一个向量来临时存储用户输入的各种游戏,并删除他们不想要的游戏。代码本身运行良好,不像方案或 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<< "\n\nPlease 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;
}

【问题讨论】:

  • 你拒绝检查你的 I/O 操作的返回值,现在你付出了代价。

标签: c++ visual-studio vector visual-studio-2013 infinite-loop


【解决方案1】:

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

请务必验证您的输入,如果无效则将其丢弃。

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

【讨论】:

  • 第一部分是正确的,但是编译器改变值或更糟的想法很奇怪。那指的是什么价值?运行时问题如何受到当时未运行的编译器的影响?
  • 编译器在运行时没有进行更改。不同编译器的不同版本会对无效数据产生不同的影响,比如将值改为0,设置一个failbit。此行为是在编译时根据版本等设置的。但是,有些只会进入失败状态并继续循环。请参阅上面附加到原始答案的链接。
猜你喜欢
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
相关资源
最近更新 更多