/* testfunc14.cpp CIS 150 2008-06-10 David Klick This program demonstrates a useful data validation function for use with menus. */ #include #include using std::cin; using std::cout; char getChoice(char* prompt, char* allowed); void displayChoice(char* msg); void cont(); int main(int argc, char* argv[]) { char choice; do { // display menu cout << "Menu\n\n" " (F)irst\n\n" " (S)econd\n\n" " (E)nd\n\n"; // get user choice choice = getChoice("Enter choice: ", "FfSsEe"); choice = toupper(choice); // convert to upper case // process choice switch (choice) { case 'F': displayChoice("the first choice"); break; case 'S': displayChoice("the second option"); break; } } while (choice != 'E'); cout << "Normal program terminiation\n\n"; cont(); return 0; } /* char getChoice(char* prompt, char* allowed); Arguments: char* prompt: a C-style string containing the prompt to show the user char* allowed: a C-style string containing all allowed user responses (each valid response being a single character) Returns: the user's choice (a character) Displays a prompt and then waits for the user to enter an allowed choice (a single character). Once a valid choice has been made, the function returns it to the calling function. */ char getChoice(char* prompt, char* allowed) { char ch; char *ptr; do { cout << prompt; cin >> ch; ptr = strchr(allowed, (int)ch); if (ptr == NULL) { cout << "Error: Invalid choice\n"; } } while (ptr == NULL); return ch; } /* void displayChoice(char* msg); Arguments: char* msg: a pointer to a C-ctyle string to be displayed Returns: nothing Displays a string sent in as being what the user has chosen. */ void displayChoice(char* msg) { cout << "You chose " << msg << '\n'; } /* void cont(); Arguments: none Returns: nothing Clears input buffer and pauses waiting for user to press Enter. */ void cont() { if (cin.rdbuf()->sungetc() != -1 && cin.get() != '\n') cin.ignore(80,'\n'); cout << "Press enter to continue..."; cin.get(); }