C programming atoi,atol,atoll stdlib.h


In C programming the <stdlib.h> atoi , atol and atoll converts the ‘const char*‘ passed to the function to the integer type.The declaration of the functions are given below

1 int atoi(const char *x);
2 long int atol(const char *x);
3 long long int atoll(const char *x); (C++11)

Parameters:
x -A pointer to const char* type or a string literal.

Return type
integer type – atoi returns ‘int’, atol returns ‘long int’ and atoll returns ‘long long’ .

Some points to note:

i) If the passed argument is a combination of number and non-number characters with the number occurring at the initial part,then only the number is converted to int ,long int or long long int type.The non-number characters part is neglected.

ii) If the argument passed is only non-number characters or the non-number character occur at first then 0 is returned.

iii) If the the string literal passed consists of a point(“.”) in between any of the number characters the characters after the point is neglected.

iv) If the function cannot represent the number after converting from the string parameter,then only the bits within the size of the return type is taken and the integer value obtain from converting the bits using the base-2 numeral method is returned.

Code example

char c1[] = “2002.9009” , c2[] = “912.56Text” , c3[ ] = “Text123” ;

printf(“%i”, atoi(c1) ) ;
printf(“\n%li”, atol(c2) ) ;
printf(“\n%lli”, atoll(c3) ) ;

Output in Visual Studio,

2002
912
0





A more exhaustive code example using atoi , atol and atoll function is shown below.

Link C math.h nan: myths and conception

Code example

#include <stdio>
#include <math.h>
#include <stdlib.h>

char* get_string()
{
return “1230”;
}

int main( )
{
printf(“%ill”, atoll( get_string() ) );

printf(“\n%lli”, atoll(“NAN”));

printf(“\n%lli”, logb( atoi(“21.3”) ));

printf(“\n%lli”, tgamma( atoll( “1200.345” )) );

getchar( );
return 0;
}

Output in VS,

1230ll
0
4616189618054758400
9218868437227405312

The ‘ll’ after the value ‘1230’ in the first output signify that the returned value is long long type,it has no other purpose but to signify the type.

Link :C programming logb,logbf,logbl math.h

Link :C programming tgamma tgammaf,tgammal math.h


Related links

->C programming atof stdlib.h