如何使用switch case c ++退出while循环

时间:2016-12-08 01:32:51

标签: c++11

当我激活案例'6'时,如何退出案例'5'?我似乎无法退出循环。我试过休息一下;案件'6'里面,但似乎没有用。

case '5': //receive a '5' from serial com port and execute auto docking
 while(1)
{
 north =0;
 south=0;
 east=0;
 west=0;
 scanmovement();
 for(index=0;index<7;index++)
  {
    getdirection(index);
  }  
  arlomove();
  obstacleavoidance();

 }
  break;
 case '6':   //receive '6' from serial com port and stop auto docking
 //somethingsomething
 //break out of while loop in case '5' when this is activated
 break;  

3 个答案:

答案 0 :(得分:1)

switch(var) // your variable
{
case '5': 
 while(1)
{
 north =0;
 south=0;
 east=0;
 west=0;
 scanmovement();
 for(index=0;index<7;index++)
  {
    getdirection(index);
  }  
  arlomove();
  obstacleavoidance();

 // var=....  update your var here     
 if(var=='6') { // do case 6 stuff
             break; // break out while when var = 6
             }
 }
  break;
 case '6':
 //somethingsomething
 //break out of while loop in case '5' when this is activated
 break;  
}

答案 1 :(得分:1)

你不能只停止案件'5',但你可以这样做。

case '5': 
  while(!stop)
  {

  } 
  break;
case '6':
  //somethingsomething
  stop = true;
  break;

答案 2 :(得分:0)

如果它在函数中,当你达到5时,你只需return

例如,

void function(int n) {
    while(1) {
        switch(n) {
            case 5:
                blahblah~~
                return;
        }
    }
}

或者,如果这是最佳选择,您可以使用goto

void main() {
    int n = 5;
    while(1) {
        switch(n) {
            case 5:
                blahblah~~
                goto theEnd;
        }
    }

    theEnd:
        blahblah~~
}