|
|
|
|
|
|
|
then your program is more portable; the test works correctly on any machine, regardless of its character set. It's a good idea to become well acquainted with these character-testing library functions (Appendix C). They can save you time and help you to write more portable programs. |
|
|
|
|
|
|
|
|
Converting Digit Characters to Integers |
|
|
|
|
|
|
|
|
Suppose you want to convert a digit that is read in character form to its numeric equivalent. Because the digit characters 0 through 9 are consecutive in both the ASCII and EBCDIC character sets, subtracting 0 from any digit in character form gives the digit in numeric form: |
|
|
|
|
|
|
|
|
For example, in ASCII, 0 has internal representation 48 and 2 has internal representation 50. Therefore, the expression |
|
|
|
|
|
|
|
|
Why would you want to do this? Recall that when the extraction operator (>>) reads data into an int variable, the input stream fails if an invalid character is encountered. (And once the stream has failed, no further input will succeed). Suppose you're writing a program that prompts an inexperienced user to enter a number from 1 through 5. If the input variable is of type int and the user accidentally types a letter of the alphabet, the program is in trouble. To defend against this possibility, you might read the user's response as a character and convert it to a number, performing error checking along the way. Here's a code segment that demonstrates the technique: |
|
|
|
|
|
|
|
|
#include <ctype.h> // For isdigit()
typedef int Boolean;
const Boolean TRUE = 1;
const Boolean FALSE = 0;
.
.
.
void GetResponse( /* out */ int& response )
// Postcondition:
// User has been prompted to enter a digit from 1
// through 5 (repeatedly, and with error messages,
// if data is invalid)
// && 1 <= response <= 5
|
|
|
|
|
|