switch case 语句不起作用吗?
所以我在一个简单的控制台应用程序中制作一个菜单。 我的代码几乎是:(底部实际代码的链接!)
int input;
bool LOOPING = true;
while(LOOPING)
{
cout << "Select an option:\n";
cout << "1 - option 1\n";
cout << "2 - option 2\n";
cout << "3 - option 3\n";
cout << "4 - option 4\n>";
cin >> input;
switch(input) {
case 1:
game();
break;
case 2:
game();
break;
case 3:
game();
break;
case 4:
game();
break;
default:
cout << "ERROR: invalid input!\nPlease enter in a number!\n\n";
break;
}
}
// rest of app...
我的问题是,程序只是进入一个不断的文本循环!为什么会发生这种情况?为什么 default:
不能阻止这种情况发生,我该如何阻止这种情况发生?
提前致谢!
编辑:要求真正的代码。
http://pastie.org/2415852
http://pastie.org/2415854
http://pastie.org/2415855
So i'm making a menu in a simple console app.
My code is pretty much: (LINKS TO ACTUAL CODE AT THE BOTTOM!)
int input;
bool LOOPING = true;
while(LOOPING)
{
cout << "Select an option:\n";
cout << "1 - option 1\n";
cout << "2 - option 2\n";
cout << "3 - option 3\n";
cout << "4 - option 4\n>";
cin >> input;
switch(input) {
case 1:
game();
break;
case 2:
game();
break;
case 3:
game();
break;
case 4:
game();
break;
default:
cout << "ERROR: invalid input!\nPlease enter in a number!\n\n";
break;
}
}
// rest of app...
My problem is, the program just goes into a constant loop of text! Why is this happening? Why does default:
not stop that from happening and how do i stop this from occuring?
Thanks in advance!
EDIT: asked for real code.
http://pastie.org/2415852
http://pastie.org/2415854
http://pastie.org/2415855
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码无限循环,因为您从未将
LOOPING
设置为 false。在真实的代码中,只有当用户选择退出时才将其设置为 false,这种情况永远不会发生,因为用户第一次输入非数字后将无法再输入。输入字符后它不会继续要求您输入的原因是
>>
不会消耗无效输入。即如果>>
应该写入int
,但用户输入的不是有效的 int,它不会写入 int,但会写入也不会从流中删除用户输入(相反,它只会设置 cin 的错误标志,您应该检查该标志)。输入将保留在流中,直到您将其写入其他地方或丢弃它。在此之前,每次读取
int
的后续尝试都会失败,因为无效输入仍在流中。Your code is looping infinitely because you never set
LOOPING
to false. In the real code you only set it to false when the user chooses to exit, which will never happen because the user is not able to enter input anymore after he inputs a non-number for the first time.The reason that it doesn't keep asking you for input after you entered a character is that
>>
does not consume invalid input. I.e. if>>
is supposed to write into anint
, but what the user enters is not a valid int, it will not write to the int, but it will also not remove the user input from the stream (instead it will simply setcin
's error flag, which you should check).The input will stay in the stream until you write it somewhere else or discard it. Until you do that every subsequent attempt to read an
int
will fail because the invalid input is still in the stream.