atoi() Function
The atoi()
function in C converts a string representing a number into its corresponding integer value. It processes the string by skipping any leading whitespace, handling an optional sign, and then reading in the digits to form the integer.
Syntax of atoi()
int atoi(const char *str);
Parameters
Parameter | Description |
---|---|
str | C-string beginning with the representation of an integral number. |
Return Value
The function returns the converted integral number as an int
value. If no valid conversion is performed, it returns 0
.
Notes
The atoi()
function begins by discarding any leading whitespace characters. It then checks for an optional plus or minus sign and converts the subsequent digits into an integer value. Any characters following the number are ignored and do not affect the conversion.
Examples for atoi()
Example 1: Converting a Basic Numeric String
This example demonstrates how atoi()
converts a simple numeric string to an integer.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char numStr[] = "12345";
int num = atoi(numStr);
printf("Converted number: %d\n", num);
return 0;
}
Explanation
- The string
"12345"
is converted to the integer12345
. - The program prints the converted number.
Output
Converted number: 12345
Example 2: Converting a String with Leading Whitespaces and a Negative Sign
This example illustrates how atoi()
handles strings that contain leading whitespaces and a negative sign.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char numStr[] = " -9876xyz";
int num = atoi(numStr);
printf("Converted number: %d\n", num);
return 0;
}
Explanation
- The function skips the leading spaces and detects the negative sign.
- The digits are then converted into the integer
-9876
, ignoring the non-numeric characters that follow.
Output
Converted number: -9876
Example 3: Handling an Invalid Numeric Conversion
This example shows the behavior of atoi()
when the input string does not begin with a valid numeric value.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char numStr[] = "abc985";
int num = atoi(numStr);
printf("Converted number: %d\n", num);
return 0;
}
Explanation
- The string
"abc985"
does not start with a numeric value. atoi()
fails to convert any portion of the string, resulting in a return value of0
.
Output
Converted number: 0