strtol() function in C++


The strol() function is used to convert the string to long integers. It sets the pointer to point to the first character after the last one. The syntax is like below. This function is present into the cstdlib library.

long int strtol(const char* str, char ** end, int base)

This function takes three arguments. These arguments are like below −

  • str: This is the starting of a string.
  • str_end: The str_end is set by the function to the next character, after the last valid character, if there is any character, otherwise null.
  • base: This specifies the base. The base values can be of (0, 2, 3, …, 35, 36)

This function returns the converted long int. When the character points to NULL, it returns 0.

Example

#include <iostream>
#include<cstdlib>
using namespace std;
main() {
   //Define two string
   char string1[] = "777HelloWorld";
   char string2[] = "565Hello";
   char* End; //The end pointer
   int base = 10;
   int value;
   value = strtol(string1, &End, base);
   cout << "The string Value = " << string1 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End << "\n"; //remaining string after long long integer
   value = strtol(string2, &End, base);
   cout << "\nThe string Value = " << string2 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End; //remaining string after long long integer
}

Output

The string Value = 777HelloWorld
Long Long Int value = 777
End String = HelloWorld
The string Value = 565Hello
Long Long Int value = 565
End String = Hello

Now Let us see the example with a different base value. Here the base is 16. By taking the string of given base, it will print in decimal format.

Example

#include <iostream>
#include<cstdlib>
using namespace std;
main() {
   //Define two string
   char string1[] = "5EHelloWorld";
   char string2[] = "125Hello";
   char* End; //The end pointer
   int base = 16;
   int value;
   value = strtol(string1, &End, base);
   cout << "The string Value = " << string1 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End << "\n"; //remaining string after long long integer
   value = strtol(string2, &End, base);
   cout << "\nThe string Value = " << string2 << "\n";
   cout << "Long Long Int value = " << value << "\n";
   cout << "End String = " << End; //remaining string after long long integer
}

Output

The string Value = 5EHelloWorld
Long Long Int value = 94
End String = HelloWorld
The string Value = 125Hello
Long Long Int value = 293
End String = Hello

Here the string is containing 5E so its value is 94 in decimal, and the second string is containing 125. This is 293 in decimal.

Updated on: 30-Jul-2019

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements