Search code examples
catoi

atoi ignores a letter in the string to convert


I'm using atoi to convert a string integer value into integer. But first I wanted to test different cases of the function so I have used the following code

#include  <stdio.h>

int main(void)
{
    char *a ="01e";
    char *b = "0e1";
    char *c= "e01";
    int e=0,f=0,g=0;        
    e=atoi(a);
    f=atoi(b);
    g=atoi(c);
    printf("e= %d  f= %d  g=%d  ",e,f,g);
    return 0;
}

this code returns e= 1 f= 0 g=0 I don't get why it returns 1 for "01e"


Solution

  • that's because atoi is an unsafe and obsolete function to parse integers.

    • It parses & stops when a non-digit is encountered, even if the text is globally not a number.
    • If the first encountered char is not a space or a digit (or a plus/minus sign), it just returns 0

    Good luck figuring out if user input is valid with those (at least scanf-type functions are able to return 0 or 1 whether the string cannot be parsed at all as an integer, even if they have the same behaviour with strings starting with integers) ...

    It's safer to use functions such as strtol which checks that the whole string is a number, and are even able to tell you from which character it is invalid when parsing with the proper options set.

    Example of usage:

      const char *string_as_number = "01e";
      char *temp;
      long value = strtol(string_as_number,&temp,10); // using base 10
      if (temp != string_as_number && *temp == '\0')
      {
         // okay, string is not empty (or not only spaces) & properly parsed till the end as an integer number: we can trust "value"
      }
      else
      {
         printf("Cannot parse string: junk chars found at %s\n",temp);
      }