How to Implement Your Own atoi() in C?
The equivalent of the atoi() function is easy to implement. One of the possible method to implement is shown below:
Approach
- Initialize res to 0.
- Iterate through each character of the string and update the res by multiplying it by 10 and keep adding the numeric value of the current digit. (res = res*10+(strg[i]-‘0’))
- Continue until the end of the string.
- return res.
Implementation of atoi() in C
C
// C program to Implement Custom atoi() #include <stdio.h> int atoi_Conversion( const char * strg) { // Initialize res to 0 int res = 0; int i = 0; // Iterate through the string strg and compute res while (strg[i] != '\0' ) { res = res * 10 + (strg[i] - '0' ); i++; } return res; } int main() { const char strg[] = "12345" ; int value = atoi_Conversion(strg); // print the Converted Value printf ( "String to be Converted: %s\n" , strg); printf ( "Converted to Integer: %d\n" , value); return 0; } |
String to be Converted: 12345 Converted to Integer: 12345
To learn more about different approaches, refer to the article – Write your own atoi()
atoi() Function in C
In C, atoi stands for ASCII To Integer. The atoi() is a library function in C that converts the numbers in string form to their integer value. To put it simply, the atoi() function accepts a string (which represents an integer) as a parameter and yields an integer value in return.
C atoi() function is defined inside <stdlib.h> header file.