Q:

C program to convert ascii to integer (atoi() implementation)

0

C program to convert ascii to integer (atoi() implementation)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will implement a function (just like atoi()) that will convert a given integer value as string into an integer value.

// C program to convert ascii to integer (atoi() implementation)

#include <stdio.h>
#include <string.h>

/*function declaration
    * name      : a2i
    * Desc      : to convert ascii to integer
    * Parameter : char* - character string 
    * return    : int 
*/
int a2i(char*);

int main()
{
    char string[5];
    printf("Enter a string value: ");
    scanf("%s", string);
    printf("\nInteger value = %d\n", a2i(string));

    return 0;
}

/*Function definition : a2i()*/
int a2i(char* txt)
{
    int sum, digit, i;
    sum = 0;
    for (i = 0; i < strlen(txt); i++) {
        digit = txt[i] - 0x30;
        sum = (sum * 10) + digit;
    }
    return sum;
}

Output:

Enter a string value: 123

Integer value = 123

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C programming Basic Input, Output, if else, Ternary Operator based Programs

Similar questions


need a help?


find thousands of online teachers now
C program to print ASCII table/chart... >>
<< C program to find remainder of two numbers without...