atol() Function
The atol()
function converts a C-string representing a numerical value into a long integer. It processes the string by ignoring any leading whitespace, then interprets an optional plus or minus sign followed by a sequence of digits, and stops at the first non-digit character. This function is commonly used for simple string-to-integer conversions in C programs.
Syntax of atol()
long int atol(const char *str);
Parameters
Parameter | Description |
---|---|
str | C-string containing the representation of an integral number. |
Return Value
The function returns the converted integral number as a long int. If the conversion fails due to the absence of a valid numerical sequence, a zero value is returned. Undefined behavior may occur if the resulting value exceeds the representable range of a long int; for robust error handling, consider using strtol()
instead.
Additional details: The function discards any leading whitespace characters, then processes an optional sign and as many digits as possible in base-10. Any characters that follow the valid numeric portion are ignored.
Examples for atol()
Example 1: Converting a Simple Numeric String
This example demonstrates the conversion of a straightforward numeric string into a long integer using atol()
.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char numStr[] = "12345";
long int num = atol(numStr);
printf("Converted number: %ld\n", num);
return 0;
}
Output:
Converted number: 12345
Example 2: Handling Leading Whitespace and Negative Numbers
This example shows how atol()
correctly handles strings with leading whitespace and an optional negative sign, converting them to the appropriate negative long integer.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char numStr[] = " -6789";
long int num = atol(numStr);
printf("Converted number: %ld\n", num);
return 0;
}
Output:
Converted number: -6789
Example 3: Ignoring Trailing Non-Numeric Characters
This example demonstrates that atol()
stops processing when non-numeric characters are encountered and ignores any trailing characters after the numeric portion.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
char numStr[] = "42abc";
long int num = atol(numStr);
printf("Converted number: %ld\n", num);
return 0;
}
Output:
Converted number: 42