In this tutorial, you will learn about C strtol()
– a string conversion function that converts a sequence of character representing an integer into long int.
We have to include stdlib.h
header file before using this function.
#include<stdlib.h>
long strtol( const char *sPtr, char **endPtr, int base );
where,
sPtr = string representing an integer number
endPtr = pointer set by the function to the next character in sPtr
after integer value
base = base of the value being converted which can be specified as 0
or any value between 2 and 36
This function returns 0
if it is unable to convert any portion of sPtr
to a long int
.
Note: Any whitespace characters at the beginning of the string are ignored.
//C string conversion function strtol
#include<stdio.h>
#include<stdlib.h>
int main()
{
//initializing string pointer
const char *sPtr = "423 student are pass";
long n; //variable to store converted sequence
char *endPtr; //char type pointer
n = strtol( sPtr, &endPtr, 0 );
printf("Original String: \"%s\"\n", sPtr);
printf("\nLong int Value: %ld"
"\nRemaining string part: %s\n", n, endPtr);
return 0;
}
Output
Explanation
In the above example, the long int
value converted from the string is stored in n
whereas, the remaining part of the string is assigned to endPtr
.
The base value 0
indicates that the converted value can be in the following format:
octal format = base 8
decimal format = base 10
hexadecimal format = base 16