while循环中的高级switch语句?

Nul*_*0rm 8 c++ logic break while-loop switch-statement

我刚刚开始使用C++但是对其他语言有一些先验知识(不幸的是,不久之后),但是有一个奇怪的困境.我不喜欢使用如此多的IF语句,并且想要使用开关/盒子,因为它看起来更干净,而且我想参与练习..但是......

让我们说我有以下场景(理论代码):

while(1) {

  //Loop can be conditional or 1, I use it alot, for example in my game
  char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      break;
    case 'b':
      cout << "...";
      break;
  }
}
Run Code Online (Sandbox Code Playgroud)

那是我的问题.假设我想退出WHILE循环,它需要两个break语句?

这显然是错误的:

case 'a':
  cout << "You entered A, which is correct";
  break;
  break;
Run Code Online (Sandbox Code Playgroud)

那么我只能在'a'上做IF语句来使用break ;? 我错过了一些非常简单的事吗?

这将解决我现在遇到的很多问题.

fre*_*low 32

我会将检查重构为另一个函数.

bool is_correct_answer(char input)
{
    switch(input)
    {
    case 'a':
        cout << "You entered A, which is correct";
        return true;
    case 'b':
        cout << "...";
        return false;
    }
    return false;
}

int main()
{
    char input;
    do
    {
        std::cout << "Enter something\n -->";
        std::cin  >> input;
    } while (!is_correct_answer(input));
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*obb 13

您可以简单地让while循环检查在一个case语句中设置的bool值.

bool done = false;    
while(!done)
{
 char something;
  std::cout << "Enter something\n -->";
  std::cin  >> something;

  //Switch to read "something"
  switch(something) {
    case 'a':
      cout << "You entered A, which is correct";
      done = true; // exit condition here
      break;
    case 'b':
      cout << "...";
      break;
  }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 5

是的,C和C++没有办法说"退出多个可破坏块"(其中"可破坏块"是任何循环或开关).解决方法包括gotos和使用布尔变量来记录外部"易碎区块"是否也应该破坏(既不优雅,但也就是生命).


Dim*_*ima 5

两个break语句不会让你退出while循环.第一个break只能让你退出switch声明而第二个永远不会到达.

假设在switch语句后循环中没有任何内容,你需要的是使while循环的条件为false .如果切换后还有其他代码,则应检查后面的条件switch,并break在那里.


bool done = false;

while(! done)
{
  // do stuff
  switch(something)
  {
    case 'a':
    done = true;  // exit the loop 
    break;
  }

  //  do this if you have other code besides the switch
  if(done)
   break;  // gets you out of the while loop

  // do whatever needs to be done after the switch

}