ADVERTISEMENT
ADVERTISEMENT

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

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

C Basic Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.