该程序旨在无限循环....所以如果有人输入 5,它会要求输入另一个数字(5 或 9),如果他/她输入 9,它会要求输入 5 或 9...无限循环.
using namespace std;
int main()
{
cout << "Hello world! Enter a number" << endl;
int x;
cin >> x;
while (x == 5)
{
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Try again, you got 5" << endl;
cin >> x;
}
while (x == 9)
{
cout << "You got 9, try again mate" << endl;
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cin >> x;
}
return 0;
}
但我不明白当我切换数字时(比如“5”到“9”再回到“5”)程序就停止了。
我认为是因为在 Loop #1 和 Loop #2 执行完后,程序再也没有返回到其中任何一个,而是继续直接“返回 0”,但我不知道如何让程序返回到两个循环。
PS:我试过切换到 do-while 循环并从括号中取出“cin”语句,但它们没有解决问题。
最佳答案
您的代码没有提供所需的行为,因为当第二个 while 循环结束时,您没有重复该过程并且程序结束。
所以您想要的是循环直到用户输入5
或 9
以外的一些数字。
为了做到这一点,我们使用 while
循环运行到无穷大,我们使用如果用户输入的数字不同于 5
或 9
,则 break 可退出无限循环。
您可以像这样修改代码:
using namespace std;
int main()
{
cout << "Hello world! Enter a number" << endl;
int x;
while(1){
cin >> x;
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
if(x == 5)
cout << "Try again, you got 5" << endl;
else if(x == 9)
cout << "You got 9, try again mate" << endl;
else
break;
}
return 0;
}
关于c++ - While 和 Do/While 循环意外中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31226712/