Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page