Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi ignores a letter in the string to convert

Tags:

c

atoi

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"

like image 837
MrsIl Avatar asked Dec 06 '22 13:12

MrsIl


2 Answers

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);
  }
like image 115
Jean-François Fabre Avatar answered Jan 01 '23 04:01

Jean-François Fabre


You are missing an opportunity: Write your own atoi. Call it Input2Integer or something other than atoi.

int Input2Integer( Str )

Note, you have a pointer to a string and you will need to establish when to start, how to calculate the result and when to end.

First: Set return value to zero.

Second: Loop over string while it is not null '\0'.

Third: return when the input character is not a valid digit.

Fourth: modify the return value based on the valid input character.

Then come back and explain why atoi works the way it does. You will learn. We will smile.

like image 20
dcy665 Avatar answered Jan 01 '23 05:01

dcy665