// // Example 8.10. Program to read a nonnegative integer one character // at a time and to print the integer or an error message // #include #include using namespace std; int main() { int getNonnegative(); int nonnegInt; // nonnegative integer user enters cout << "Enter a nonnegative integer and press return." << endl; cout << "Do not use a sign and only type digits." << endl; cout << "Your nonnegative integer: "; nonnegInt = getNonnegative(); if (nonnegInt < 0) cout << "Sorry, input line is invalid." << endl; else cout << "Your nonnegative integer is " << nonnegInt << "." << endl; return 0; } // // Function to read characters, verifying that they are digits, // and to accumulate the digits into a nonnegative integer. // The function does not check for integer overflow. // Pre: none // Post: A nonnegative integer was returned; or in the case // of an error, -1 was returned. // int getNonnegative() { const int NEWLINE = '\n'; int nonnegInt; // nonnegative integer user enters bool inputOK; // boolean value for continuing loop char ch; // character input from user cin >> ch; // skip over white space at beginning of line // Verify each character input is a digit and accumulate nonnegInt = 0; inputOK = true; while (!isspace(ch) && inputOK) { if (isdigit(ch)) // in number, accumulate and cont. { nonnegInt = nonnegInt * 10 + ch - '0'; cin.get(ch); } else // Error: character not a digit { cout << ch << " is not a digit." << endl; inputOK = false; } } // If number valid, make sure nothing else on line. while (ch != NEWLINE && inputOK) { if (isspace(ch)) cin.get(ch); else // Error: additional values on line { cout << "Have only one integer per line." << endl; inputOK = false; } } // Error detected. Last processed character not NEWLINE if (!inputOK) { nonnegInt = -1; cin.ignore(256, '\n'); } return nonnegInt; }