Quick links
Write a C program to input string representation of integer and convert string to long using atol() function. How to convert string to long using atol() function.
Also check atoi() library function in C.
atol() library function
atol() function converts string representation of integer to long type. It is defined in stdlib.h header file.
Syntax of atol() function
long int atol (const char * str);- It accepts pointer to constant character
stri.e. the sting representation of integer. - It returns
long int. Ifstris a valid integer string then it returnsstraslong inttype otherwise return0L.
Important note:
atol()function behaviour is undefined, if integer represented bystrunderflows or overflowslong intrange. Use more robust and reliable strtol() function to convert string tolong inttype.- The function ignores leading and trailing whitespaces.
- It also ignores all leading and trailing alphabets and special characters.
Example program to use atol() function
/**
* C program to convert string to long using atol() library function.
*/
#include <stdio.h>
#include <stdlib.h> // Used for atol()
int main()
{
char number[30];
long bigNum;
/* Input string representation of integer from user. */
printf("Enter any integer: ");
fgets(number, 30, stdin);
/* Convert string representation of number to integer */
bigNum = atol(number);
/* Use %d, %i, %l, %ld, %li to print long type */
printf("Converted long int = %ld\n", bigNum);
return 0;
}Output
Enter any integer: 12 Converted long int = 12 Enter any integer: 999999999 Converted long int = 999999999 Enter any integer: -999999999 Converted long int = -999999999 Enter any integer: a Converted long int = 0 Enter any integer: 1 2 3 Converted long int = 1 Enter any integer: aaaaaaaaaaaaaasdddddddddd Converted long int = 0 Enter any integer: 1.533 Converted long int = 1 Enter any integer: -99999999999999999999999999999 Converted long int = 1610612737 Enter any integer: 99999999999999999999999999999999999 Converted long int = -1 Enter any integer: 11111111a Converted long int = 11111111 Enter any integer: aaaaa111111111 Converted long int = 0
Happy coding 😉