//************************************************************************** // 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 valid int -- pre-test version // // 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) { cin >> i; while (cin.fail()) { cout << "Invalid integer entered!! Reenter -- "; cin.clear(); // clear the error flag clrStream(); // clear bad data from the stream cin >> i; } } //************************************************************************** // function to get a valid int -- post-test version -- requires a flag!!! // // 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) { bool ok = true; do { cin >> i; if (cin.fail()) { cout << "Invalid integer entered!! Reenter -- "; cin.clear(); // clear the error flag clrStream(); // clear bad data from the stream ok = false; // set our flag to stay in loop } } while (!ok); } //************************************************************************** // function to get a valid int -- alternate version using an infinite loop // // 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 (true) { cin >> i; if (cin.good()) break; // valid int extracted so exit cout << "Invalid integer entered!! Reenter -- "; cin.clear(); // clear the error flag clrStream(); // clear bad data from the stream } }