这可能只需要基本的问题解决技能,但是我试图创建一种非常简短的方法:要求用户提供输入,并且仅在输入至少通过一次条件检查之后才说输入不合法。一个do while循环似乎很合适。
我在下面的实现方式始终会产生一个问题,即1个特定的数字会产生一个错误,即如果用户输入0,但您没有收到应有的消息,我可以将其更改为一个非常特殊的数字,但仍会在前面最终的错误仍然存在。我来自Java背景,其中null是使此操作变得容易的默认值,但是由于效率原因,在c ++中似乎不是这种情况。我可以声明一个,bool
但这似乎是一种过多的解决方法。
这是我现在拥有的代码:
int birthYear = 0;
do {
if (birthYear != 0) cout << "Your input " << birthYear << " is not a legit birthday";
cout << "What is the year you were born?: "; cin >> birthYear;
} while (birthYear < 1900 || birthYear > 2100);
这是一个经典示例,其中while
“ do
/ ”和“ /”while
循环都不是完全合适的,因为您需要在检查循环条件之前和之后做一些事情。
将您的循环重写为break
中间是的“永远”循环:
for (;;) {
cout << "What is the year you were born?: ";
cin >> birthYear;
if (birthYear >= 1900 && birthYear <= 2100) {
break;
}
cout << "Your input " << birthYear << " is not a legit birthday";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句