【问题标题】:How to exit out of a while loop using switch case c++如何使用Switch Case C ++退出循环
【发布时间】:2017-04-23 03:45:52
【问题描述】:

当我激活案例“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;  

【问题讨论】:

  • 请编辑您的代码以显示退出 while 循环的某些原因,最好是 if 语句。
  • 所以要明确一点,这是多线程的还是以其他方式可重入的(例如,通过信号处理程序,或case '5': 循环中调用的方法之一)?因为否则,您将永远无法到达case '6': 来终止循环。
  • 我已经编辑了代码
  • 这是在函数内部吗?
  • 是的,它在主函数的while循环中运行

标签: c++11


【解决方案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;  
}

【讨论】:

    【解决方案2】:

    你不能只是停止案例'5',但你可以做这样的事情。

    case '5': 
      while(!stop)
      {
    
      } 
      break;
    case '6':
      //somethingsomething
      stop = true;
      break;
    

    【讨论】:

    • 您在回答中提出的建议不会让循环永远持续下去。
    【解决方案3】:

    如果它在函数中,您可以在达到 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~~
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多