Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

c++ - how to exit nested loops

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...