While 循环转义范围
我有一个 while 循环,当我点击数字 1 到 5 时,我希望逃脱。
对此最好的声明是什么?
我目前有这个。
while ( oneChoice!= 1 || oneChoice!= 2 || oneChoice!= 3 || oneChoice!= 4 || oneChoice!= 5 )
{
cout << "Please make a selection" << endl;
cout << "Choose once more: ";
cin >> oneChoice;
break;
}
I have a while loop i wish to escape when i hit the number 1 through 5.
What would be the best statement to put for that?
I currently have this.
while ( oneChoice!= 1 || oneChoice!= 2 || oneChoice!= 3 || oneChoice!= 4 || oneChoice!= 5 )
{
cout << "Please make a selection" << endl;
cout << "Choose once more: ";
cin >> oneChoice;
break;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会这样做:
中断位于中间,以便仅当用户输入可接受范围之外的值时才打印错误消息。
for (;;)
是适合您不希望在顶部或底部测试退出条件的循环的 C 族习惯用法。I'd do it like this:
The break goes in the middle so that the error message is printed only if the user enters a value outside the acceptable range.
for (;;)
is proper C-family idiom for a loop where you don't want to have an exit condition tested at the top or bottom.假设
oneChoice
是int
(例如,因此不能有 1 到 2 之间的值),只需将条件更改为:or,等价:
另外,if
oneChoice
在进入循环之前没有真正的意义或重要性,使用do { ... } while (oneChoice < 1 || oneChoice > > ) 可能是更好的做法。 5);
改为循环。Assuming
oneChoice
is anint
(and thus can't have a value between 1 and 2, for example), just change the conditional to:or, equivalently:
Additionally, if
oneChoice
has no real meaning or importance before entering the loop, it would probably be better practice to use ado { ... } while (oneChoice < 1 || oneChoice > 5);
loop instead.