In C, the atoi()
function converts a string to an integer.
The syntax for the function is given below:
int atoi(const char *string)
The function takes as input the string that is to be converted to an integer.
If successfully executed, the function returns the integer value.
If the string starts with an alphanumeric character or only contains alphanumeric characters, 0 is returned.
In case the string starts with a numeric character but is followed by an alpha-numeric character, the string is converted to an integer until the occurrence of the first alphanumeric character
Note: The
stdlib.h
library must be included for theatoi()
function to be executed
Let’s look at an example to further understand the working of the atoi()
function:
#include<stdio.h>#include <stdlib.h>int main() {// Converting a numeric stringchar str[10] = "122";int x = atoi(str);printf("Converting '122': %d\n", x);// Converting an alphanumeric stringchar str2[10] = "Hello!";x = atoi(str2);printf("Converting 'Hello!': %d\n", x);// Converting a partial stringchar str3[10] = "99Hello!";x = atoi(str3);printf("Converting '99Hello!': %d\n", x);return 0;}
Line 2: We include stdlib.h
to execute the atoi()
function.
Lines 6-8: In this section of the code we first intialized an charactor array with the name of str
in which we stored a value of 122
, and in the line 7 we converted that array to an integar with the help of atoi()
function.
Lines 11-13: We initializes a character array str2
with the value "Hello!". Then it uses the atoi
function to convert the string "Hello!" to an integer. However, since the string "Hello!" cannot be converted to a valid integer, atoi
returns 0.
Lines 16-18: In this section we initializes a character array str3
with the value "99Hello!". Then it uses the atoi
function to convert the string "99Hello!" to an integer. However, atoi
stops converting when it encounters the first non-numeric character, which is 'H' in this case. So it only converts "99" to an integer, resulting in 99.
Free Resources