How to convert a string to an integer in C
In C, the atoi() function converts a string to an integer.
Syntax
The syntax for the function is given below:
int atoi(const char *string)
Parameters
The function takes as input the string that is to be converted to an integer.
Return value
-
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.hlibrary must be included for theatoi()function to be executed
Example
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.hto execute theatoi()function.Lines 6-8: In this section of the code we first intialized an charactor array with the name of
strin which we stored a value of122, and in the line 7 we converted that array to an integar with the help ofatoi()function.Lines 11-13: We initializes a character array
str2with the value "Hello!". Then it uses theatoifunction to convert the string "Hello!" to an integer. However, since the string "Hello!" cannot be converted to a valid integer,atoireturns 0.Lines 16-18: In this section we initializes a character array
str3with the value "99Hello!". Then it uses theatoifunction to convert the string "99Hello!" to an integer. However,atoistops 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