Exercise 3-4 (Menu with switch statements)

Chapter_3     Exercise_3-3 GoTo     Exercise_3-5







Exercise 3-4     TCP1, p. 227


Modify Menu1.cpp (see ch3-Menu) to use switch() statements instead of if() statements.





// A menu using 3 switch statements
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int main()
{
char c; // To hold the response (input from keyboard)
bool quit = false; // Flag for quitting

while(quit == false)
{
cout << "MAIN MENU:" << endl;
cout << "l: left, r: right, q: quit -> ";
cin >> c;

switch (c)
{
case 'q':
cout << "Quitting menu..." << endl;
quit = true; // to exit while()
break; // from (outer) switch()

case 'l':
cout << "LEFT MENU:" << endl;
cout << "Select a or b: ";
cin >> c;

switch (c)
{
case 'a':
cout << "You chose 'a'" << endl;
break; // out of first inner switch()
case 'b':
cout << "You chose 'b'" << endl;
break; // out of first inner switch()
default:
cout << "You didn't choose a or b!" << endl;
break; // out of first inner switch()
} // end of first inner switch()

break; // from outer switch(), back to main menu

case 'r':
cout << "RIGHT MENU:" << endl;
cout << "Select c or d: ";
cin >> c;

switch (c)
{
case 'c':
cout << "You chose 'c'" << endl;
break; // out of second inner switch()
case 'd':
cout << "You chose 'd'" << endl;
break; // out of second inner switch()
default:
cout << "You didn't choose c or d!" << endl;
break; // out of second inner switch()
} // end of second inner switch()

break; // from outer switch(), back to main menu

default:
cout << "You must type l or r or q!" << endl;
break; // from outer switch(), back to main menu
} // end of outer switch()
} // end of while()

return 0;
} // end of main()
/*
g++ Menu3.cpp -o Menu3
./Menu3
MAIN MENU:
l: left, r: right, q: quit -> n
You must type l or r or q!
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: a
You chose 'a'
MAIN MENU:
l: left, r: right, q: quit -> l
LEFT MENU:
Select a or b: c
You didn't choose a or b!
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: d
You chose 'd'
MAIN MENU:
l: left, r: right, q: quit -> r
RIGHT MENU:
Select c or d: q
You didn't choose c or d!
MAIN MENU:
l: left, r: right, q: quit -> q
Quitting menu...
*/









Chapter_3     Exercise_3-3 BACK_TO_TOP GoTo     Exercise_3-5



Comments

Popular posts from this blog

Contents