for switch

I wrote the following program... I didn't compile it yet because I am looking for the way to break a loop from switch statement. I tried Google, but no results... Any ideas? thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
    for(char ans;;)
    {
           cout << "Again(y/n)?\n";
           cin >> ans; cin.ignore(10000, '\n'); cin.clear();
           switch(ans)
           {
                      case 'Y':
                      case 'y': ExecuteTask(); break;
                      case 'N':
                      case 'n': break; //Here. I want to break the loop if(ans == 'n' || ans == 'N')
                      default : cout << "Invalid input!\n";
           }
    }
for (char ans = 'Y'; ans != 'N' && ans != 'n'; )
Variable ans can't have two values, so that && should be ||. Anyway, that is not what I want. I could use simply while for that and big if/else statements, but I wanted to do it this way :)
@Zexd

Variable ans can't have two values, so that && should be ||.


Expression ans != 'N' && ans != 'n' means that ans is equal to neither 'N' nor 'n'. So using && is correct opposite to ||.
My bad, didn't see that != ...

I am still interested in answer to my question (breaking a loop from switch).
Last edited on
I showed you how to exit the loop. If you wnat something else then insert an explicit if statement.
eh... I just want to know is it possible to break a loop from the switch ._.

I know I can use many other ways, but I want to learn as much as possible.
Except the goto statement you can not exit simultaneously the switch and the loop statements.
There is always the return instruction. From the looks of your snippet, you want to break out of the loop when the user wants to end the program, yes?
yeah, but if I return 0, the program will end. There might be some info to write like total number of times the loop was executed or the sum of something used in program. Anyway, thanks.
something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
   bool bStillGoing = true;
   while(bStillGoing)
    {
           cout << "Again(y/n)?\n";
           cin >> ans; cin.ignore(10000, '\n'); cin.clear();
           switch(ans)
           {
                      case 'Y':
                      case 'y': ExecuteTask(); break;
                      case 'N':
                      case 'n':
                        bStillGoing = false;
                       break; //Here. I want to break the loop if(ans == 'n' || ans == 'N')
                      default : cout << "Invalid input!\n";
           }
    }
Last edited on
Topic archived. No new replies allowed.