Nested switch
A
case alternative within a
switch can be associated with any
sequence of
statements, which might include other
switch statements. For example:
int a;
cin >> a;
switch(a)
{
case 1:
cout << "Enter a character, please ";
char b;
cin >> b;
switch(b)
{
.
.
.
}
break;
case 2:
cout << "you entered 2";
break;
case 3:
cout << "you entered 3";
break;
default:
cout << "you did not enter either 1, 2 or 3";
}
if
a’s value is 1, a value for
b is
read and the second
switch statement
is executed.
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a value, please ";
int a;
cin >> a;
switch(a)
{
case 1:
cout << "Enter a character, please ";
char b;
cin >> b;
switch(b)
{
case 'a':
cout << "you entered \'a\'";
break;
case 'b':
cout << "you entered \'b\'";
break;
default:
cout << "you entered neither \'a\' nor \'b\'";
}
break;
case 2:
cout << "you entered 2";
break;
case 3:
cout << "you entered 3";
break;
default:
cout << "you did not enter either 1, 2 or 3";
}
}
(Possible) Output
Enter a value, please 1
Enter a character, please d
you entered neither 'a' nor 'b'