#include using namespace std; // function prototypes void clrStream(); // clear to end of line char getResponse(char defalt); void getValid(int& i); // obtain a valid int from the user int main() { char answer; do { int sum = 0; int value; do { getValid(value); if (cin) sum += value; } while (!cin.eof()); cout << "The sum is " << sum << endl; cout << "Would you like to do another sum (No to stop)? "; cin.clear(); // reset eof flag } while (getResponse('Y') != 'N'); return 0; } //************************************************************************** // function to clear the data from the cin stream up to and including the // next new line character. //************************************************************************** void clrStream() { while (cin.peek() != '\n') cin.ignore(); cin.ignore(); // ignore the newline as well } //************************************************************************** // function to get a character response from the user and use the default // response if the user just hits the return key // /// \param [in] defalt imports the default character to use if the enter /// key is pressed /// \returns defalt if the next character in the cin stream is a new line, /// otherwise it returns the character entered /// \post the cin stream is cleared //************************************************************************** char getResponse(char defalt) { char ch = cin.get(); if (ch == '\n') ch = defalt; // use the default character else clrStream(); // clear the newline and any garbage entered return ch; } //************************************************************************** // function to get a valid int // // parameter usage -- i exports the integer obtained // // post-condition -- i is a valid integer and the cin stream marker is left // at the first character after the extracted integer //************************************************************************** void getValid(int& i) { while (!(cin>>i || cin.eof())) { cout << "Invalid integer entered!! Reenter -- "; cin.clear(); // clear the error flag clrStream(); // clear bad data from the stream } } // while (!(cin>>i) && !cin.eof()) { // alternate version of while loop