1

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;
}
Jens
  • 69,818
  • 15
  • 125
  • 179
Lee Carlton
  • 25
  • 1
  • 1
  • 5
  • 4
    `b`'s not a decimal digit. – Mat Dec 07 '12 at 06:59
  • 1
    Just see this one - http://stackoverflow.com/questions/2729460/why-do-i-get-this-unexpected-result-using-atoi-in-c?rq=1 – nightlytrails Dec 07 '12 at 07:01
  • Firstly, C is a case-sensitive language. So that should be `atoi`, not `ATOI`. Secondly, in the body of your question you are talking about some `ATOL` function. So, is it `ATOI` or `ATOL`? – AnT stands with Russia Dec 07 '12 at 07:05
  • Even though `atoi` is convenient for cases where you can handle non-numeric input as 0 instead of error, you should probably learn `strtol` too, in most use cases you will need to use it anyway. – hyde Dec 07 '12 at 08:50

2 Answers2

6

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

  • oh ok, that makes sense -- so it has to begin with an integer. I see what you mean, i thought it was able to grab an integer from any string regardless of the characters. Thanks! – Lee Carlton Dec 07 '12 at 14:59
2

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?

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765