// while.cxx #include #include #include // needed to use isdigit() etc. using std::cout; using std::cin; using std::endl; int main() { char readchar; int numeral, number = 0; cout << "Program to read integers safely:" << endl; cout << "Enter an integer" << endl; // STRIP OUT ALL LEADING NON-DIGIT CHARACTERS // Read and discard characters as long as they are not digits readchar = cin.get(); while( !isdigit( readchar ) ) readchar = cin.get(); // READ THE DIGITS, CONSTRUCT THE INTEGER // Read characters as long as they are digits/numerals while( isdigit(readchar) ) { // Convert the read character to a numeral numeral = readchar - '0'; // To make the new numeral the units digit, // multiply current integer by 10 and add new numeral to it number = number * 10 + numeral; readchar = cin.get(); } // Print the constructed integer cout << number << endl; return EXIT_SUCCESS; }