Quick links
Write a C program to input string representation of integer and convert string to long using strtol() library function. How to convert string to long using strtol() library function in C programming?
strtol() library function
strtol() function is used to convert string representation of integer to long type. It is defined in stdlib.h header file. It is more flexible and reliable then atol() function.
strtol()lets you to specify base of input string. You can use this function to convert integer string of any base tolongtype.- Using
strtol()you can easily distinguish between successful or failed conversion.
Syntax of strtol() function
long strtol(const char* str, char** endPtr, int base);- It accepts pointer to constant character
stri.e. string representaiton of integer to be converted. - Next it accepts a pointer to char pointer
endPtr. On successendPtrpoints to first character after number otherwise is aNULLpointer. - Finally it accept an integer
baseof input string. - The function on success return converted integer as
longtype and setsendPtrto point to first character after converted integer. Otherwise returns zero (0L) if no valid conversion can be performed and setsendPtrtoNULLpointer.
Note: Unlike
atol(), it efficiently handles integer underflow and overflows. It returnsLONG_MINorLONG_MAXon integer underflows or overflows respectively.Also see how to find minimum and maximum limit of a data type?
Example program to use strtol() function
/**
* C program to convert string to long using strtol() library function.
*/
#include <stdio.h>
#include <stdlib.h> // Used for strtol()
int main()
{
char number[30];
char* endPtr;
long bigNumber;
int base;
/* Input string representation of number from user. */
printf("Enter any number: ");
fgets(number, 30, stdin);
/* Input base */
printf("Enter base: ");
scanf("%d", &base);
/* Convert string representation of number to long */
bigNumber = strtol(number, &endPtr, base);
/* endPtr points to NULL for failed conversions */
if(*endPtr)
printf("Unable to convert '%s' to base %d.", number, base);
else
printf("Converted long = %ld\n", bigNumber);
return 0;
}Output
Enter any number: 22 Enter base: 10 Converted long = 22 Enter any number: CA10 Enter base: 16 Converted long = 51728 Enter any number: 054 Enter base: 8 Converted long = 44 Enter any number: 1001 Enter base: 2 Converted long = 9 Enter any number: error Enter base: 10 Unable to convert 'error' to base 10.
Happy coding 😉