如何在c ++满足某些条件(if)后重启while循环?

use*_*022 2 c++ if-statement while-loop

我在while循环中有很多if语句,程序必须根据条件打印错误消息,但如果有多个错误,则必须只有其中一个.

Sin*_*all 7

你的问题不是很详细,所以有点难以确定你想要什么.

如果希望while循环在任何错误触发后进入下一次迭代,则应使用以下continue语句:

while( something )
{
    if( condition )
    {
        //do stuff
        continue;
    }
    else if( condition 2 )
    {
        //do other stuff
        continue;
    }
    <...>
}
Run Code Online (Sandbox Code Playgroud)

如果if循环内没有其他东西,并且条件是整数值,则应考虑使用switch:

while( condition )
{
    switch( errorCode )
    {
        case 1:
        //do stuff;
        break;
        case 2:
        //do other stuff;
        break;
        <...>
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想完全重启周期......那么这有点困难.由于你有一个while循环,你可以将条件设​​置为它的起始值.例如,如果你有这样的循环:

int i = 0;
while( i < something )
{
    //do your stuff
    i++;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样"重置"它:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,你应该非常小心,很容易意外地得到一个无限循环.