c++ - 在 c++ 中满足某些条件(如果)后,如何重新启动 while 循环?

标签 c++ if-statement while-loop

<分区>

我在 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/

相关文章:

delphi - 在 **if 语句** 中使用 **and** 运算符

c - "if ... else if ... else ..."在语义上与 "if ... else { if ... else ...}"有什么不同吗?

c++ - 第三方dll丢失,等待中怎么办?

c++ - 函数不将数据存储到结构数组

vba - 如何查看 if 语句中正在比较的内容

c - 尽管使用 continue,While 循环会无限地卡在 else 语句中

linux - 重命名文件的shell脚本

javascript - 为什么我的 do/while 循环偶尔会运行失败?

c++ - 如何编写模板?

c++:类外的模板变量