[英]Why doesn't this output “Please try again” when loop runs again?
Hello I am trying to learn c++ and I wanted to give a little practice with a program. 您好,我正在尝试学习c ++,我想对程序进行一些练习。 However I'm having trouble using cout within the loop. 但是我在循环中使用cout有麻烦。
This is the loop I'm trying to output text from. 这是我试图从中输出文本的循环。 When the user enters a number that isn't valid it is supposed to say "Sorry try again!" 当用户输入无效的数字时,应该说“抱歉,请重试!”
while (datecheck)
{
bool check(false);
if (check)
std::cout<<"Sorry try again!"<<std::endl;
std::cin>>c;
if (c >= 1)
{
if (b == 2 && c <= 28)
datecheck = false;
if (b == 2 && a % 4 == 0 && c <= 29)
datecheck = false;
if (b == 4 || b == 6 || b == 9 || b == 11 && c <= 30)
datecheck = false;
if (c <= 31)
datecheck = false;
}
check = true;
}
When it outputs and I purposely keep myself in the loop it doesn't output anything 当它输出时,我故意使自己陷入循环中,它什么也不输出
Year: -20
-20
-20
You declare a fresh new variable check
at every iteration. 您在每次迭代时声明一个新的新变量check
。 And you initialize that variable to false
every time. 然后,您每次都会将该变量初始化为false
。 So move that declaration before the while loop. 因此,将该声明移到while循环之前。
Change this: 更改此:
while (datecheck)
{
bool check(false);
...
check = true;
}
to this: 对此:
bool check(false);
while (datecheck)
{
...
check = true;
}
The problem is with declaration of bool check(false);
问题在于bool check(false);
声明bool check(false);
. 。 This keeps on re-assigning value to false
at beginning of each iteration. 在每次迭代开始时,这都会继续将值重新分配为false
。
A simple fix could be to get-rid of use of check
variable and use only datecheck
. 一个简单的解决方法是datecheck
使用check
变量,而仅使用datecheck
。
bool datecheck(true);
while (true)
{
std::cin>>c;
if (c >= 1)
{
if (b == 2 && c <= 28)
datecheck = false;
if (b == 2 && a % 4 == 0 && c <= 29)
datecheck = false;
if (b == 4 || b == 6 || b == 9 || b == 11 && c <= 30)
datecheck = false;
if (c <= 31)
datecheck = false;
}
if (datecheck)
{
std::cout<<"Sorry try again!"<<std::endl;
}
else
{
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.