atoi,atol and atof functions

These functions are available under stdlib.h .These are very unknown functions.Lets see what these do..


atol()
atol returns the value in terms of long datatype of the string containing numbers.the syntax is
atol(stringvariable)
ex: consider the following program


#include<stdio.h>
#include<conio.h>
void main() 

{
char a[10],b[10];
puts("Enter the value of a");
gets(a);
puts("Enter the value of b");
gets(b);
printf("%s+%s=%ld and %s-%s=%ld",a,b,(atol(a)+atol(b)),a,b,(atol(a)-atol(b)));
getch();
}
  
#include<stdio.h>
#include<conio.h> 
main()
{
char a[]={"2545.965"};
printf("atol=%ld\t atof=%f\t atoi=%d\t\n",atol(a),atof(a),atoi(a));
}


now consider this
As you can see 0XA is a hexadecimal number(hexadecimal number in C is written by writing 0X(zero X) folowed by hex number).It's decimal equivalent is 10.The following is the output i got in Red hat

and similarly there is atof() which returns the float value of the string containing numbers and atoi() which returns integer value.


now to see the difference between the 3 look at this program
the output will be
atol=2545 atof=2545.965000 atoi=2545
The output of atoi() and atol() functions will be same but atof() function may give different output depending upon the compiler.That is,in some compiler the output may be like this atof=2545.96498 or something.The above output is extarcted from red hat


let's look what happens when the string does not contain numeric value.change this statement in the above program
char a[]={"adithya"};
now when you run the program the following will be the output
atol=0 atof=0 atoi=0
that means the string should contain numeric value
now modify this program as
char a[]={"007adi"};
the output in this case(tested in Red hat) will be
atol=7 atof=7.000000 atoi=7
so the functions has taken 007 only not the remaining part
However note that this depends upon compiler.Some will take ,while some will give output as 0.


Now consider this
char a[]={"adi007"};
the output of the program will be
atol=0 atof=0.000000 atoi=0
I'm not sure of this but the following is the point that i noticed
char a[]={"0XA"};
what do you think the output is???
atol=0 atof=10.000000 atoi=0
Now the question is why atol and atoi couldn't understand this while atof took the number as hex number?????

About This Blog

There is something for everyone. !! A tech blog on various topics. Let it be devops, programming etc; we have it all covered here in layman terms :)

Total Pageviews

Back to TOP