/* asst04.cpp 7/6/2005 CIS 150 David G. Klick Solution to assignment #4. */ #include #include using std::cin; using std::cout; using std::fixed; using std::showpoint; using std::setprecision; // function prototypes char getChoice(char* prompt, char* allowed); void displayMenu(char* menu); double calcRectangle(); double calcTriangle(); double calcCircle(); double calcHexagon(); double getDouble(char* prompt, double min, double max); int main(void) { char choice; double area; bool valid; char *menu = "Area Calculator Menu:\n\n" " (R)ectangle\n\n" " (C)ircle\n\n" " (H)exagon\n\n" " (T)riangle\n\n" " E(x)it\n\n"; do { // display menu displayMenu(menu); // get user choice choice = getChoice("Enter choice: ", "RrCcTtHhXx"); choice = toupper(choice); valid = true; // process choice switch (choice) { case 'R': area = calcRectangle(); break; case 'C': area = calcCircle(); break; case 'H': area = calcHexagon(); break; case 'T': area = calcTriangle(); break; default: valid = false; } // display area if appropriate if (valid) { cout << "The area is " << fixed << showpoint << setprecision(2) << area << "\n\n"; } // continue while user did not choose to exit } while (choice != 'X'); return 0; } void displayMenu(char *mnu) { cout << mnu; } 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; } double calcRectangle() { double length, width; length = getDouble("Enter length (0-300): ", 0.0, 300.0); width = getDouble("Enter width (0-300): ", 0.0, 300.0); return length * width; } double calcTriangle() { double height, base; height = getDouble("Enter height (0-200): ", 0.0, 200.0); base = getDouble("Enter base (0-200): ", 0.0, 200.0); return 0.5 * height * base; } double calcCircle() { const double PI = 3.1415926536; double radius; radius = getDouble("Enter radius (0-250): ", 0.0, 250.0); return PI * radius * radius; } double calcHexagon() { double side; side = getDouble("Enter side (0-200): ", 0.0, 200.0); return side * side * 2.598075; } double getDouble(char *prompt, double min, double max) { double num; do { cout << prompt; cin >> num; if (nummax) { cout << "Error: Input above maximum\n"; } } while (nummax); return num; }