atoi()
is a pre-defined library function in C programming that converts a string of characters to an integer value. The function is specified in the header file stdlib.h
. The function accepts only one parameter as an argument, which is a pointer to a string. The string is passed as const
, which ensures that the function doesnt change the value of the string and only returns the integer value from the string. The function skips all the white space characters at the starting of the string and converts the characters as the number part and stops when it finds the first non-number character. If the passed string has non-valid input, the function returns 0. The function is useful for converting a string argument to an integer.
The syntax of atoi()
function is as follows:
int atoi(const char *str)
Here, str
is the string representation of an integral number, and the function returns the converted integral number as an int
value. If no valid conversion could be performed, it returns zero.
Example usage of atoi()
function:
#include <stdio.h>
#include <stdlib.h>
int main() {
int val;
char str[] = "1234";
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
return 0;
}
Output:
String value = 1234, Int value = 1234