// // Example 8.4. Interactive program to square numbers. // The user is asked if he or she wishes to square a number // and responds with y/n. // #include const int YES = 'y'; const int NO = 'n'; int main(void) { char GetAnswer(void); // prototypes int ReadNum(void); int n; // number to be squared char answer; // answer for wanting to square answer = GetAnswer(); // ask if want to square while (answer == YES) { n = ReadNum(); // get next number cout << n << " squared is " << n * n << "\n\n"; answer = GetAnswer(); // ask if want to square } cout << "Thank you.\n"; return 0; } // // Function to ask if user wishes to continue and to return // the user's response after flushing the input buffer // Pre: none // Post: A 'y' or 'n' user response was returned. // char GetAnswer(void) { char answer; // answer for wanting to square do { cout << "Do you want to square a number? (y/n) "; cin.get(answer); if (answer != '\n') cin.ignore(256, '\n'); } while (answer != YES && answer != NO); return answer; } // // Function to prompt for and read an integer to return // Pre: none // Post: An integer input was returned. // int ReadNum(void) { int n; // input number cout << "Enter an integer to be squared: "; cin >> n; cin.ignore(256, '\n'); // advance buffer pointer past newline return n; }