Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced switch statement within while loop?

I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But..

Lets say I have the following scenario (theorietical code):

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;
  }
}

And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements?

This obviously looks wrong:

case 'a':
  cout << "You entered A, which is correct";
  break;
  break;

So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple?

This would solve a lot of my problems that I have right now.

like image 920
Nullw0rm Avatar asked May 07 '10 04:05

Nullw0rm


People also ask

Can we use switch-case inside while loop?

Yes a switch statement can be used inside a loop.

Can you do a switch statement within a switch statement?

It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Why nested switch statements should be avoided?

Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.


1 Answers

I would refactor the check into another function.

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));
}
like image 195
fredoverflow Avatar answered Sep 20 '22 13:09

fredoverflow