【问题标题】:how to exit nested loops如何退出嵌套循环
【发布时间】:2013-09-11 06:40:02
【问题描述】:

我有类似的东西

   while(playAgain==true)
   {
      cout<<"new game"<<endl; //i know 'using namespace std;' is looked down upon
      while(playerCard!=21)
      {
          *statements*
          if(decision=='n')
          {
              break
          }
       ...
      }
   }

但是当我想跳出两个循环时,那个 break 只会跳出第一个 while 循环

【问题讨论】:

  • 设置一个标志,检查它,如果再次设置中断......
  • 您可以使用goto 语句跳转到循环外的标签.... 我当然是在开玩笑:)。最好的解决方案是避免嵌套的 if(带有break 的 if),并将条件(decission == 'n')放在两个循环中。

标签: c++ loops while-loop break


【解决方案1】:

不要煮意大利面并将循环提取到函数中:

void foo(...) {
    while (...) {
        /* some code... */
        while (...) {
            if ( /* this loop should stop */ )
                break;
            if ( /* both loops should stop */ )
                return;
        }
        /* more code... */
    }
}

这种分解还将产生更简洁的代码,因为您将拥有不同抽象级别的简洁函数,而不是数百行丑陋的程序代码。

【讨论】:

  • 当使用了太多变量但在循环之外(在原始函数中)定义时,它有一个不足,这意味着您必须通过foo()'s参数传递这些变量
【解决方案2】:

基本上有两种选择。

  1. 在外循环中添加条件检查。

    while ((playAgain==true) &amp;&amp; (decision != '\n'))

  2. 只需使用goto。人们经常被告知永远不要使用goto,就好像它是怪物一样。但我不反对用它来退出多个循环。在这种情况下,它是干净利落的。

【讨论】:

    【解决方案3】:

    使用转到:

       while(playAgain==true)
       {
          cout<<"new game"<<endl; //i know 'using namespace std;' is looked down upon
          while(playerCard!=21)
          {
              *statements*
              if(decision=='n')
              {
                  goto label;
              }
           ...
          }
       }
       label: 
       ...    
    

    【讨论】:

      【解决方案4】:
       while(playAgain==true && decision !='n' ){
                                 ^^ add a condition
            cout<<"new game"<<endl; 
            while(playerCard!=21){
            *statements*
            if(decision=='n'){
                break
               }
           ...
            }
       }
      

      【讨论】:

        【解决方案5】:

        此解决方案特定于您的情况。当用户的决定是'n'时,他不想再玩了。所以只需将playAgain 设置为false 然后中断。外循环会自动断开。

        while(playAgain==true){
           cout<<"new game"<<endl; //i know 'using namespace std;' is looked down upon
           while(playerCard!=21){
              *statements*
              if(decision=='n'){
                 playAgain = false; // Set this to false, your outer loop will break automatically
                 break;
              }
           }
        }
        

        【讨论】:

          【解决方案6】:

          如果你不必避免goto声明,你可以写

          while (a) {
              while (b) {
                  if (c) {
                      goto LABEL;
                  }
              }
          }
          LABEL:
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-26
            • 2011-10-02
            • 1970-01-01
            • 2016-04-17
            • 1970-01-01
            • 1970-01-01
            • 2022-09-24
            • 1970-01-01
            相关资源
            最近更新 更多