C++ String::stol() function



The C++ std::string::stol() function is used to convert a string to a long integer. It takes a string as input and convert it to a long type, with an optional base parameter for numeric conversion. Additionally, it take a pointer to a size_t to store the nuber of characters processed. If the conversion is failed, it throws an invalid_argument exception.

Syntax

Following is the syntax for std::string::stol() function.

 long stol (const string& str, size_t* idx = 0, int base = 10); long stol (const wstring& str, size_t* idx = 0, int base = 10); 

Parameters

  • str − It indicates the string object with the representation of a integral number.
  • idx − It indicates the pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value.
  • base − It indicates the numerical base that determines the valid character and their interpretation.

Return value

It returns a string as the value into a long integer.

Example 1

Following is the basic example to convert a decimal string into a long int using C++.

 #include <iostream> #include <string> using namespace std; int main() { string decimal = "123456"; long int dec_num = stol(decimal); cout << "The long integer = " << dec_num << endl; return 0; } 

Output

If we run the above code it will generate the following output.

 The long integer = 123456 

Example 2

In this example, we are passing a hexadecimal string to convert into a long int.

 #include <iostream> #include <string> using namespace std; int main() { string hex = "987654F"; long int hex_num = stol(hex, nullptr, 16); cout << "The long integer = " << hex_num << endl; return 0; } 

Output

If we run the above code it will generate the following output.

 The long integer = 159868239 

Example 3

This program extracts a long integer from a string containing alphanumeric characters, stopping at the first non-numeric character, and prints the integer to the complier.

 #include <iostream> #include <string> using namespace std; int main() { string mixed = "10000px"; size_t pos; long int number = stol(mixed, & pos); cout << "The long integer = " << number << endl; return 0; } 

Output

Following is the output of the above code.

 The long integer = 100000 

Example 4

This program converts a base-24 string 64B to its equivalent long integer value.

 #include <iostream> #include <string> using namespace std; int main() { string base24 = "64B"; long int base24_num = stol(base24, nullptr, 24); cout << "The long integer = " << base24_num << endl; return 0; } 

Output

Following is the output of the above code.

 The long integer = 3563 
string.htm
Advertisements