The atoi()
function in C is used to convert a string (array of characters) into its integer representation. The name atoi
stands for “ASCII to Integer”. This function is declared in the stdlib.h
header file.
Syntax:
int atoi(const char *str);
Parameters:
str
: A pointer to a null-terminated string representing the number to be converted.
Return Value:
- Returns the integer value represented by the string.
- If the string doesn’t represent a valid number, the function returns
0
.
Key Points:
- Whitespace Handling: Leading whitespaces (spaces, tabs, etc.) are ignored.
- Sign Handling: It can handle both positive and negative numbers (e.g.,
"-123"
will return-123
). - Non-Numeric Characters: If the string contains non-numeric characters (other than the optional leading ‘+’ or ‘-‘ and the digits), conversion stops at the first invalid character, and the integer value up to that point is returned.
- Overflow and Underflow: In case of overflow or underflow, the result is implementation-dependent, though it may return a value that fits the limits of
int
.
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
const char *str1 = "12345";
const char *str2 = " -5678";
const char *str3 = "abc123"; // Invalid string
// Using atoi() to convert strings to integers
int num1 = atoi(str1);
int num2 = atoi(str2);
int num3 = atoi(str3); // Will return 0 because the string starts with non-numeric characters
printf("String '%s' converts to %d\n", str1, num1);
printf("String '%s' converts to %d\n", str2, num2);
printf("String '%s' converts to %d\n", str3, num3);
return 0;
}
Output:
String '12345' converts to 12345
String ' -5678' converts to -5678
String 'abc123' converts to 0
Notes:
atoi()
does not handle errors robustly. If you want better error handling (e.g., checking if the conversion succeeded), you can usestrtol()
instead, which provides more control over the conversion process.