Converting a String to a Numeric Type - C++ Data Type

C++ examples for Data Type:string

Introduction

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.

Demo Code

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

long hex2int(const string& hexStr) {
   char *offset;/*from  w  w w.  j av  a2 s . c  o m*/
   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;
}

Result

strtol and strtoul work the same way; the only difference is the return type.

strtod is similar, but does not allow you to specify a base.


Related Tutorials