3.1. Converting a String to a Numeric Type
Problem
You have numbers in string
format, but you need to convert them to a numeric type, such as an int
or float
.
Solution
You can do this in one of two ways, with standard library functions or with the
lexical_cast
class in Boost (written by Kevlin
Henney). The standard library functions are cumbersome and unsafe, but they are standard,
and in some cases, you need them, so I present them as the first solution. lexical_cast
is safer, easier to use, and just more fun, so I
present it in the discussion.
The functions strtol
, strtod
, and strtoul
, defined in <cstdlib>
, convert a null-terminated character string to
a long
int
, double
, or
unsigned
long
. You can use them to convert numeric strings of
any base to a numeric type. The code in Example
3-1 demonstrates a function, hex2int
, that you
can use for converting a hexadecimal string to a long
.
Example 3-1. Converting number strings to numbers
#include <iostream> #include <string> #include <cstdlib> using namespace std; long hex2int(const string& hexStr) { char *offset; if (hexStr.length() > 2) { if (hexStr[0] == '0' && hexStr[1] == 'x') { return strtol(hexStr.c_str(), &offset, 0); } } return strtol(hexStr.c_str(), &offset, 16); } int main() { string str1 = "0x12AB"; cout << hex2int(str1) << endl; string str2 = "12AB"; cout << hex2int(str2) << endl; string str3 = "QAFG"; cout << hex2int(str3) << endl; }
Here’s the output from this program:
4779 4779 0
The first two strings both contain the hexadecimal ...
Get C++ Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.