C Reference function atoi() convert a string to an integer
This function of stdlib will convert a string to an integer.
Usage of atoi():
int atoi ( const char * str );
Parameters:
C string str interpreting its content as a integer. White-spaces are discarded until the first non-whitespace character is found.
Return value:
The function returns the converted integral number as an int value, if successful. If no valid conversion could be performed then an zero value is returned. If the value is out of range then INT_MAX or INT_MIN is returned.
Source code example of atoi():
#include<stdio.h>
#include<stdlib.h>
int main ()
{
int i;
char buffer [256];
printf ("Enter a number: ");
fgets (buffer, 256, stdin);
i = atoi (buffer);
printf ("The value entered is %d.",i);
return 0;
}
Output of the atoi example program above:
Enter a number:12
The value entered is 12.
This entry was posted in C Reference stdlib.h Functions.
You can follow any responses to this entry through the RSS 2.0 feed.
Both comments and pings are currently closed.
Tweet This! or use
to share this post with others.
best answer i got here……..thankyou!!!
i didnt understand the fgets arguments..
i tried using atoi but geting an error saying TYPE MISMATCH IN PARAMETER ‘_S’ IN CALL TO ATOL….can anybody help me out?
I mean for example if the user will input the word “eleven” the output must be 11?
@rebecca: NO! It’s just that, if a number is stored in form of string, atoi() will convert it into an integer, so now you can perform integral operations on it.
eg: char *str = “11”; //you cannot perfrom mathematical operations on str
int x = atoi(str); //now x will contain numerical value 11
What happens if you need to include 0 in your input range?
what if the user inputs “A”…..will atoi() return the ascii value of A ??
@abhi
It will return 0 not the ASCII value of the character.
if we want to convert string into integer For Example we have str[]= “a1b2c3” we want 1 as an integer so just subtract the ASCII value of zero from the ASCII value of 1.
code
int a=str[1]-‘0’;
how to get 12 from string a12b?
@bhaghath pj, that’s what atoi does.
What if I have multiple numbers stored in the array, let’s say s[]=”abc1def23ghi90″ and I have to store them seperately for further usage?
Would this be possible with atoi?
I want implementation code for function atoi()
@bhaghath pj… Easy way to write code like this…(just only get for 12 from a12b.. You can change this different ways).
int i;
char x[]=”a12b”;
i=atoi(&x[1]);
printf(“%d\n”,i);
Hi all,
i need to convert asci to integer without using atoi function…(inputs “12a” or “bgdd”…
What if I have multiple numbers stored in the array, let’s say s[]=”1def3ghi0″ and I have to store them seperately for further usage?
Would this be possible with atoi???????????????????????