for switch

May 30, 2013 at 9:44pm
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";
           }
    }
May 30, 2013 at 9:50pm
for (char ans = 'Y'; ans != 'N' && ans != 'n'; )
May 30, 2013 at 9:55pm
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 :)
May 30, 2013 at 10:20pm
@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 ||.
May 30, 2013 at 10:24pm
My bad, didn't see that != ...

I am still interested in answer to my question (breaking a loop from switch).
Last edited on May 30, 2013 at 10:24pm
May 30, 2013 at 10:28pm
I showed you how to exit the loop. If you wnat something else then insert an explicit if statement.
May 30, 2013 at 10:33pm
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.
May 30, 2013 at 10:51pm
Except the goto statement you can not exit simultaneously the switch and the loop statements.
May 30, 2013 at 11:37pm
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?
May 31, 2013 at 1:37pm
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.
May 31, 2013 at 2:15pm
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 May 31, 2013 at 2:16pm
Topic archived. No new replies allowed.