The atoi function is part of the C standard library. Its primary use is to parse a string and convert its contents to the corresponding numerical value of int type.
This tutorial will discuss how to use the atoi function to convert strings to integer values in C.
Basic Usage
The syntax for the atoi function is:
This function accepts a single parameter, which is a pointer to the string to convert. This value is a constant; thus, the function does not alter the original string.
The function returns the converted string to its equivalent integer type.
How it Works
The atoi function works by removing all possible whitespace characters—similar to the isspace function—until it encounters the first non-whitespace character.
After the first non-whitespace, it assigns an optional sign (positive or negative). Next, it parses all the possible base-10 values until it encounters a non-numerical character. This could be a null-terminating character.
Finally, it interprets the values into their corresponding integer type.
Atoi Function Example
The function below shows how to use the atoi function in C.
The program above asks the user to provide a number and reads the value from stdin. Next, we parse its contents to an integer using the atoi function.
The result is:
i is 232
Conclusion
This quick tutorial has walked you through how to use the atoi function to convert a string to an integer in C.