【发布时间】:2015-11-10 02:48:03
【问题描述】:
各位,为什么这段代码会变成无限循环?我正在学习 C++,所以如果你能解释解决方案,对我来说非常重要!
// Odd_or_Even.cpp : This program determinate if a number is Odd or Even
//
#include "stdafx.h"
#include "std_lib_facilities.h";
int main()
{
int num = 0;
bool repeat = true;
while (repeat == true)
{
cout << "Please enter an integer to determinate if it's odd or even: ";
cin >> num;
cout << "\nReading data...";
if (!cin) {
cout << "Failed\n";
cout << "There is some problem with the number, sorry!\n";
cout << "\n";
cin.clear();
}
else
{
cout << "God job, now stop lose time.";
repeat = false;
}
}
keep_window_open();
return 0;
}
谢谢!
编辑:好的,我写了 if for 阻止循环,但是如果你尝试写一个字母,而不是一个数字,它仍然会进入一个循环!
【问题讨论】:
-
你应该有一行将在 if 语句中将 repeat 的值更改为 false
-
是的,我知道,但我希望当我说“对不起”时它会回到顶部并重复,而不是输出变为无限:cout
-
如果回到开始提示另一个值,你建议什么时候结束循环?
-
@RavenJe 有可用的
else子句,您可以在哪里设置repeat = false;?这是什么愚蠢的问题? -
@RavenJe 好的,至于您的编辑,您需要致电
cin.clear()处理失败案例,以便能够再次获得输入。
标签: c++ loops while-loop infinite-loop repeat