121: Computer Science 1 --- Lecture Monday, January 28

Topics:
Top-down Design

Repetition and Control
Sentinel values
Bullet proofing
ASCII
I/O processing

It is good programming practice to make programs as bulletproof as possible,
i.e, not susceptible to user error. For example we can read in numeric
data as a sequence of characters, check for bad characters and convert
to the corresponding number. In the next example, we do just this for reading
in an integer.

Problem: write a program which will ignore non-digit data, and covert a sequence of digits to a numeric integer value. For example if the
session input is: ###1237###  then the program should output the number: 1237

Top Down Design:
Step 1: repeatedly read character until a digit ('0' ..'9') is encountered.
Step 2: repeatedly read digit characters until a non-digit is encountered
  Step 2.a: for each digit convert it to an integer and add it to the previously converted sequence
                 note that we must multiply the previous number by 10 with each iteration

#include <iostream> 

using namespace std; 

int main()
{
    
   char c;
   
   cout << "\nPlease enter a positive integer: ";


// Step 1 of the input processing to ignore non-digit data
   cin >> c;
   while (c < '0' || c > '9')
       cin >> c;
// Now we have the first digit
// Step 2 is to convert the digits to numeric values
    int Number = 0;
     while ( c >= '0' && c <= '9') {
        Number = Number*10 + static_cast< int >(c)
                            - static_cast< int >( '0' );
        cin >> c;
   } //END while
  
        cout << "\nNumber is  " << Number << '.' << endl;
 
 
   return 0;
} //END
Now suppose we don't want the user to have to enter a non-white space  sentinel such as a '#'. We can take the sentinal to be the escape sequence '\n'. However, we must replace the statement cin >> c; with cin.get(c). Try to see if you can modity the code to take this into account.