Reputation: 25
I'm just getting started out with C and I'm trying to learn the ATOL function. Can someone tell me why it keeps printing a 0? I know that means that the conversion can't be performed, but I'm not sure why.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i = atoi (" bl149");
printf("%d\n", i);
return 0;
}
Upvotes: 1
Views: 19644
Reputation: 406
atoi basically convert a string having a number in to integer one and whatever it will convert that will become the return value for it. OR to be more precise atoi function start checking from the beginning of string. if it has digit(from the begining only) then it will return that value in integer. Below example will clear the concept For example
atoi("1234")
--> it will convert string "1234" in to integer and return it
--> i.e. ouput is 1234
atoi("1234abcd") --> i.e. ouput is 1234
atoi("a1234abcd") --> i.e. ouput is 0
In your case since your string starting from b (" b1149") so it will return 0
Upvotes: 7
Reputation: 320531
What exactly don't you understand? " bl149"
is not a valid representation of a number. So, atoi
returns 0
as it always does in case of erroneous input. That's all there is to it.
A valid representation can begin from a sequence of whitespace characters, but it must be followed by an optional +/-
and a sequence of decimal digits. Your whitespace sequence is followed by b
. b
is not a decimal digit.
How did you expect it to work? What did you expect that atoi
to do in this case?
Upvotes: 2