The C programming language contains a collection of useful functions that we can use to perform actions in our program. One such function is the atoi function.

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:

int atoi(const char *str);

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.

#include

#include

int main() {


    int i;


    char str[100];


    printf(“Enter a number: “);


    fgets(str, 100, stdin);


    i = atoi(str);


    printf(“i is %d”, i);


    return 0;

}

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:

Enter a number: 232


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.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/john-150×150.png611b08187aecd.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list