/////////////////////////////////////////////////////////////////////// // Template .C File for reading doubles, ints and chars // /////////////////////////////////////////////////////////////////////// #include double readDouble() // Safer way to read a double { double num; cin >> num; while(cin.fail()) // check for format errors { // in executing previous statement cin.clear(); // clear up the input stream cin.ignore(80, '\n'); // ignore remaining characters on the line cout << "Please enter the number correctly: "; cin >> num; } cin.ignore(80, '\n'); // ignore remaining characters on the line return num; } int readInt() // Safer way to read an int { int n; cin >> n; while(cin.fail()) // check for format errors { // in executing previous statement cin.clear(); // clear up the input stream cin.ignore(80, '\n'); // ignore remaining characters on the line cout << "Please enter the integer correctly: "; cin >> n; } cin.ignore(80, '\n'); // ignore remaining characters on the line return n; } void readIntViaRef(int& n) { cin >> n; while(cin.fail()) // check for format errors { // in executing previous statement cin.clear(); // clear up the input stream cin.ignore(80, '\n'); // ignore remaining characters on the line cout << "Please enter the integer correctly: "; cin >> n; } cin.ignore(80, '\n'); // ignore remaining characters on the line return; } char readChar() // safer way to read a single character { char c; cin >> c; cin.ignore(80, '\n'); // ignore remaining characters on the line return c; } int main() { char c; double diameter; int n; int nRef; // for entering via reference parameter cout << "Enter one character: " << endl; c = readChar(); cout << "Enter diameter: "; diameter = readDouble(); cout << "Enter an integer: "; n = readInt(); cout << "Enter another integer: "; readIntViaRef(nRef); cout << "Integers entered: " << n << " and " << nRef << endl; return 0; }