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 string char str[10] = "122"; int x = atoi(str); printf("Converting '122': %d\n", x); // Converting an alphanumeric string char str2[10] = "Hello!"; x = atoi(str2); printf("Converting 'Hello!': %d\n", x); // Converting a partial string char str3[10] = "99Hello!"; x = atoi(str3); printf("Converting '99Hello!': %d\n", x); return 0; }
RELATED TAGS
View all Courses