在 C++ 中满足某些条件(如果)后如何重新启动 while 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12740268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how can i restart while loop after certain condition (if) satisfied in c++?
提问by fhuseynli
i have a lot of if statements in while loop, program has to print error messages according to conditions, but if there are more than one error it has to be only one of them.
我在 while 循环中有很多 if 语句,程序必须根据条件打印错误消息,但如果有多个错误,它必须只是其中之一。
回答by SingerOfTheFall
Your question isn't very detailed so it's a little hard to tell what exactly do you want.
你的问题不是很详细,所以很难说出你到底想要什么。
If you want the while loop to go to the next iteration after any error has fired, you should use the continue
statement:
如果您希望 while 循环在触发任何错误后进入下一次迭代,则应使用以下continue
语句:
while( something )
{
if( condition )
{
//do stuff
continue;
}
else if( condition 2 )
{
//do other stuff
continue;
}
<...>
}
If nothing else than these if
s is inside the loop, and the conditions are integer values, you should consider using switch
instead:
如果if
循环内只有这些s,并且条件是整数值,则应考虑switch
改用:
while( condition )
{
switch( errorCode )
{
case 1:
//do stuff;
break;
case 2:
//do other stuff;
break;
<...>
}
}
If you want to completely restart the cycle... well this is a little harder. Since you have a while
loop, you can just set the condition to it's starting value. For example, if you have a loop like this:
如果你想完全重新开始循环......好吧,这有点难。由于您有一个while
循环,您可以将条件设置为它的起始值。例如,如果你有一个这样的循环:
int i = 0;
while( i < something )
{
//do your stuff
i++;
}
then you can "reset" it like this:
然后你可以像这样“重置”它:
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
}
}
However, you should be really careful with this, it's easy to get an infinite loop accidentally.
但是,您应该非常小心,很容易意外获得无限循环。
回答by madhairsilence
String errorMessage = "No Error";
while( cond){
if( cond 1) {
errorMessage = " Error 1"
}
if( cond 1) {
errorMessage = " Error 1"
}
if( cond 1) {
errorMessage = " Error 1"
}
if( cond 1) {
errorMessage = " Error 1"
}
}
If you want to break after any error that is encountered, use break
如果您想在遇到任何错误后中断,请使用 break
If you want to ignore the current iteration after any error is encountered , use continue
如果您想在遇到任何错误后忽略当前迭代,请使用 continue
If you want to terminate the execution after any error is encountered, use exit
如果您想在遇到任何错误后终止执行,请使用 exit