C function to convert a string to an integer

C already has this function which is called atoi .(ascii to integer). If your string is "124", your function returns 124. If your string is "11aa88", the function returns 11 and if the string is "aa" the function returns 0

Let us write our own version of it.


int string_to_int(char *str)
{
     int num=0;
     while(*str >='0' && *str<='9')
     {
            int digit = *str-'0';
            num = num*10 +digit;
            str++;
       }
       return num;
}

Not very difficult isn't it? First we are initializing our number to 0. Then we loop as long as character is a digit i.e. it is >= '0' and it is <='9'. We extract one digit and subtract ASCII code of 0 from it. (If the number was "178", first digit is 1 which when stored as a character will be '1' , but its numerical value is 49). To the previous number we   add this digit after multiplying by 10.  (If our earlier value is 1 and current digit is 7, we use 1x10 + 7) Next we move on to the next digit by incrementing str.
   Notice that this logic takes care of non-numerical string as well. As first character of string will be non-digit, the while loop is not executed and we return 0 from the function.
   The next question is, how do we take care of negative numbers. The above function returns 0 if the number is negative. Let us do some trick. Let us look at the first character. If it is '-', let us remember it and negate the number later.


#include<stdio.h>
int string_to_int(char*str);
int main()
{
     char str[10]="";
     int n;
     while(strcmp(str,"0")!=0)
     {
          printf("Enter a string - 0 to stop");
          scanf("%s",str);
          n = string_to_int(str);
          printf("The number is %d\n",n);
     }
     return 0;
}
   

int string_to_int(char *str)
{
     int num=0,negative=0;
     if(*str=='-')
     {
          negative = 1;
          str++;
     }
     while(*str >='0' && *str<='9')
     {
            int digit = *str-'0';
            num = num*10 +digit;
            str++;
       }
      if(negative)
      {
        num = -num;
      }
       return num;
}


Comments

Popular Posts