为什么在C++(Visual Studio)中,control+P会导致无限循环
Why is control + P leading to infinite loop in C++ (Visual Studio)?
我已经编程了一段时间(用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
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 连接线程时的无限循环
- 为什么这种方法会进入无限循环?
- 由于QTextStream的无限循环
- Qt 在另一个线程中无限循环
- 从文件 C++ 读取时的无限循环
- 为什么在C++(Visual Studio)中,control+P会导致无限循环