C++ Primer Plus Chapter 6 Exercise 3

c plus plusExercise 3 is interesting because it shows us how a rudimentary menu can be made using simple switch statements. Check out the source for my solution:

3. Write a precursor to a menu-driven program. The program should display a menu offering
four choices, each labeled with a letter. If the user responds with a letter other than
one of the four valid choices, the program should prompt the user to enter a valid
response until the user complies. Then the program should use a switch to select a simple
action based on the user’s selection. A program run could look something like this:
Please enter one of the following choices:
c) carnivore p) pianist
t) tree g) game
Please enter a c, p, t, or g: q
Please enter a c, p, t, or g: t
A maple is a tree.

#include <iostream>

using namespace std;

void showMenu();
void carnivore();
void tree();
void pianist();
void game();

int main()
char choice;

cin >> choice;
while(choice != 'Q' && choice != 'q')
case 'C':
case 'c': carnivore();
case 'P':
case 'p': pianist();
case 'T':
case 't': tree();
case 'G':
case 'g': game();
default: cout << "That is not a choice!\n";
cin >> choice;
return 0;

void showMenu()
cout << "Please enter one of the following choices: \n\n";
cout << "c) carnivore p) pianist\n";
cout << "t) tree      g) game\n";
cout << "q) quit\n";
cout << "\n";

void carnivore()
cout << "Rawr, you have selected carnivore!\n";

void tree()
cout << "Behold, a tree has spawned!\n";

void pianist()
cout << "Is this Beethoven?\n";

void game()
cout << "Shall we play a game?\n";

2 thoughts on “C++ Primer Plus Chapter 6 Exercise 3

  1. why you using functions?? this is next chapter

    • Hi, thanks for commenting. If you will turn to page 50 in the text, you will see basic functions are introduced to the reader there. User-defined functions and their usage examples are introduced just a few pages later. Yes, the actual chapter on functions comes next, but that goes much further in depth than what is needed here. You are not the first person to make this observation and I would be interested to see your non-function solution as a comment. Mind you, If you have made it this far in the book, functions should not be completely foreign to you. One last thing, I think you will find that most C++ courses do briefly run though all the common concepts of C++ first before separating them out in depth just as this book has.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s