How to convert string to int without using library functions in c





How to convert string to int without using library functions in c programming language

#include<stdio.h>

int stringToInt(char[] );
int main(){
  
    char str[10];
    int intValue;

    printf("Enter any integer as a string: ");
    scanf("%s",str);

   intValue = stringToInt(str);

    printf("Equivalent integer value: %d",intValue);

    return 0;
}

int stringToInt(char str[]){
    int i=0,sum=0;

    while(str[i]!='\0'){
         if(str[i]< 48 || str[i] > 57){
             printf("Unable to convert it into integer.\n");
             return 0;
         }
         else{
             sum = sum*10 + (str[i] - 48);
             i++;
         }

    }

    return sum;

}

Sample output:
Enter any integer as a string: 123
Equivalent integer value: 123






5 comments:

  1. while(str[i]!='\0'){
    if(str[i]< 48 || str[i] > 57){
    printf("Unable to convert it into integer.\n");
    return 0;
    }
    else{
    sum = sum*10 + (str[i] - 48);
    i++;
    }

    for this part, i do not understand the str[i] is smaller than 48 and larger than 57?
    Can you explain it again?

    ReplyDelete
  2. str[i] will return ASCII value of that character. ASCII value of '0' is 48 and '9' is 57.

    ReplyDelete
  3. can any one write the full c program for day number for example 04-feb-2012 must be printed as 35 2012
    means jan as 31 days so 31+4=35

    ReplyDelete
  4. how can i print prime number in if else condition with out using loop;

    ReplyDelete
  5. may i put
    sum = sum*10 + (str[i] );
    instead of
    sum = sum*10 + (str[i] - 48); ?
    and here 48 means 0?

    ReplyDelete