Quick links
Write a C program to input string from user and convert string to long long using strtoll() library function. How to convert string to long long int using strtoll() library function in C programming?
strtoll() library function
strtoll() library function is used to convert string representation of integer to long long int type. It is defined in stdlib.h header file.
It was added with C11 standard (update your compiler with C11 standard support to use this function).
Syntax of strtoll() function
long long int strtoll(const char* str, char** endPtr, int base);- First parameter
stris a pointer to constant character. It contains string to be converted tolong long inttype. - Next it accepts pointer to character pointer. On successful conversion
endPtrpoints to first character after number otherwise is set toNULLpointer. - Next parameter is
baseof input string. - On success the function returns converted integer as
long long inttype and setsendPtrto first character after number. On failure it return0LLand setendPtrtoNULL.
Note:
strtoll()efficiently handles integer underflows and overflows. It returnsLONG_LONG_MINorLONG_LONG_MAXif underflow or overflow.Also learn how to find minimum and maximum range of a type?
Example program to use strtoll() function
/**
* C program to convert string to long long int using strtoll() library function.
*/
#include <stdio.h>
#include <stdlib.h> // Used for strtoll()
int main()
{
char number[30];
char* endPtr;
long long int bigNumber;
int base;
/* Input string representation of number from user. */
printf("Enter any number: ");
fgets(number, 30, stdin);
printf("Enter base: ");
scanf("%d", &base);
/* Convert string representation of number to long long */
bigNumber = strtoll(number, &endPtr, base);
/* endPtr points to NULL for failed conversion */
if(*endPtr)
printf("Unable to convert '%s' to base %d.", number, base);
else
printf("Converted long long int = %lld\n", bigNumber);
return 0;
}Output
Enter any number: 9223372036854775807 Enter base: 10 Converted long long int = 9223372036854775807 Enter any number: abfcee12 Enter base: 16 Converted long long int = 2885479954 Enter any number: 0776743 Enter base: 8 Converted long long int = 261603 Enter any number: 0111100110 Enter base: 2 Converted long long int = 486 Enter any number: 922337203685477999999999 Enter base: 10 Converted long long int = 9223372036854775807 Enter any number: -922337203685477599999 Enter base: 10 Converted long long int = -9223372036854775808 Enter any number: error Enter base: 10 Unable to convert 'error' to base 10.
Happy coding 😉