how to exit nested loops

2019-02-25 19:24发布

i have something like

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

but that break only breaks out of the first while loop when I want to break out of both of the loops

6条回答
2楼-- · 2019-02-25 19:52

This solution is specific to your case. When the user's decision is 'n', he doesn't want to play again. So just set playAgain to false and then break. Outer loop will be broken automatically.

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;
      }
   }
}
查看更多
做自己的国王
3楼-- · 2019-02-25 20:00
 while(playAgain==true && decision !='n' ){
                           ^^ add a condition
      cout<<"new game"<<endl; 
      while(playerCard!=21){
      *statements*
      if(decision=='n'){
          break
         }
     ...
      }
 }
查看更多
你好瞎i
4楼-- · 2019-02-25 20:01

Use goto:

   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: 
   ...    
查看更多
爷的心禁止访问
5楼-- · 2019-02-25 20:04

Don't cook spaghetti and extract your loops into the function:

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

this decomposition will also yield cleaner code since instead of hundreds of lines of ugly procedural code, you will have neat functions at different levels of abstraction.

查看更多
放我归山
6楼-- · 2019-02-25 20:06

There are basically two options to go.

  1. Add the condition check in outer loop.

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

  2. Simply use goto. People are often told never to use goto as if it's monster. But I'm not opposed to use it to exit multiple loops. It's clean and clear in this situation.

查看更多
爷的心禁止访问
7楼-- · 2019-02-25 20:12

If you don't have to avoid goto statement, you can write

while (a) {
    while (b) {
        if (c) {
            goto LABEL;
        }
    }
}
LABEL:
查看更多
登录 后发表回答