Converting
Strings to Numbers
|
Required header: #include
<stdlib.h>
It may be necessary to convert numbers stored in
strings to a numeric data type. Here are three functions that will
enable you to perform this task:
1. atoi(s) |
pronounced "ASCII to integer"
converts character s to an integer. |
|
Examples:
apstring starship = "1701 D Class";
int j = atoi(starship.c_str());
cout<<j; //will
print 1701
apstring address = "RR 3 Box
448";
int j = atoi(address.c_str());
cout<<j; //will
print 0
|
2. atol(s) |
converts character s to a long integer |
3. atof(s) |
converts character s to a floating point number. |
|
|
NOTE:
The apstrings will need to be converted
to traditional C++ strings for these functions.
(use string.c_str()) |
Remember, numbers stored in
strings must be converted to a numeric type (such as int) before they
can be used in calculations. |
|