C atoi function: The function atoi converts a string to a integer(int). The function skips all white-space characters at the beginning of the string until the first non-whitespace character is found. Then it converts the subsequent characters into a integer number until it finds a character which is not a digit. It also takes an optional initial plus or minus sign before first base-10 digit in string.
Function prototype of atoi
int atoi(const char *str);
- str : A pointer to a string beginning with the representation of an integer number.
Return value of atoi
atoi in c: This function returns the converted integer number as an int value otherwise it returns zero(0), If no valid conversion could be performed.
C program using atoi function
atoi c: The following program shows the use of atoi function for string to integer conversion.
#include <stdio.h> #include <stdlib.h> int main(){ char string[100]; int value; printf("Enter a string\n"); scanf("%s", &string); /* String to Integer conversion */ value = atoi(string); printf("Integer value %d\n", value); return 0; }
Output
Enter a string 1234 Integer value 1234
Enter a string 1234.555 Integer value 1234
Enter a string 1234ABCD Integer value 1234
Enter a string ABCD Integer value 0