I've just completed an exercise from a book wherein the task is to display a menu of choices each associated to an alphabetical character. The program is to reject invalid characters and only finishing when a valid choice is made. Below is my solution, it achieves the task but I'd like to know if there is a completely easier approach.
// chap05q03.cpp
// C++ Primer Plus, Fifth Edition
// Chapter 6, Page 276.
// Programming Exercise # 3
// 4 Dec, 2007.
#include <iostream>
int main()
{
using namespace std;
char ch;
char msg[] = "\nPlease enter c, p, t or g: ";
bool invalid = true;
cout << "Please enter on of the following choices:\n\n";
cout << "c) carnivore p) pianist\n";
cout << "t) tree g) game\n";
while (invalid)
{
cin >> ch;
if ((ch != 'c') && (ch != 'p') && (ch != 't') && (ch != 'g'))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << msg;
}
else
invalid = false; // we've got a correct entry, exit loop.
}
switch (ch)
{
case 'c' : cout << "Option 'c' selected"; break;
case 'p' : cout << "Option 'p' selectd"; break;
case 't' : cout << "Option 't' selected"; break;
case 'g' : cout << "Option 'g' selected"; break;
default : cout << "It will never get her"; break;
}
system("PAUSE");
return 0;
}
Any advice welcome.