<分区>
我在 while 循环中有很多 if 语句,程序必须根据条件打印错误消息,但如果有多个错误,则只能是其中一个。
<分区>
我在 while 循环中有很多 if 语句,程序必须根据条件打印错误消息,但如果有多个错误,则只能是其中一个。
最佳答案
您的问题不是很详细,因此很难说出您到底想要什么。
如果您希望 while 循环在任何错误触发后转到下一次迭代,您应该使用 continue
语句:
while( something )
{
if( condition )
{
//do stuff
continue;
}
else if( condition 2 )
{
//do other stuff
continue;
}
<...>
}
如果循环内只有这些 if
,并且条件是整数值,您应该考虑改用 switch
:
while( condition )
{
switch( errorCode )
{
case 1:
//do stuff;
break;
case 2:
//do other stuff;
break;
<...>
}
}
如果你想完全重新开始循环……好吧,这有点难。由于您有一个 while
循环,您可以将条件设置为它的起始值。例如,如果您有这样的循环:
int i = 0;
while( i < something )
{
//do your stuff
i++;
}
然后你可以像这样“重置”它:
int i = 0;
while( i < something )
{
//do your stuff
if( something that tells you to restart the loop )
{
i = 0;//setting the conditional variable to the starting value
continue;//and going to the next iteration to "restart" the loop
}
}
但是,你应该非常小心,很容易意外地进入无限循环。
关于c++ - 在 c++ 中满足某些条件(如果)后,如何重新启动 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12740268/