In this section, we will learn what the atoi() function is and how to use it in C.
String to int in C: atoi() Function
If we have a character-string that contains only numbers, we can use the `atoi()` function to get this number as an integer type.
The function’s prototype is in `stdlib.h` header file and so we need to include this header file in order to use the function.
atoi() Function Syntax
Here’s the prototype of the `atoi()` function:
int atoi(const char *str)
atoi() Function Parameters
This function takes one argument and that is the address of the character-string that we want to get its integer value.
atoi() Function Return Value
The return value of this function is the integer value of the character-string or 0 if the operation was un-successful (in case the character-string didn’t contain number for example).
Example: convert String to int c
#include <stdio.h> #include <stdlib.h> int main() { char * pointer = "234234"; int result = atoi(pointer); printf("The result is: %d",result); return 0; }
Output:
The result is: 234234
Example: c string to integer
#include <stdio.h> #include <stdlib.h> int main() { char * pointer = "f234234tes"; int result = atoi(pointer); printf("The result is: %d",result); return 0; }
Output:
The result is: 0
Note: in the `stdlib.h` header file, there are two other functions named `atof()` and `atol()` by which we can convert a string to a double and long type, respectively.
Both of the functions have the same prototype as the `atoi()` function has.
Example: convert string to double in c
#include <stdio.h> #include <stdlib.h> int main() { char * pointer = "234.33"; double result = atof(pointer); printf("The result is: %f",result); return 0; }
Output:
The result is: 234.33