atol() in C - Source Code Example

In this source code example, we will see how to use the atol() function in C programming with an example.

atol() Function Overview

The atol() function in C converts a string to a long integer. It's found in the <stdlib.h> library. 

If the function finds a character that isn't part of a valid number, it stops. If no valid number starts the string, it returns 0.

Source Code Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Valid number as a string
    char numStr1[] = "1234567890";
    long num1 = atol(numStr1);
    printf("%s to long integer: %ld\n", numStr1, num1);

    // String starts with a valid number
    char numStr2[] = "98765xyz";
    long num2 = atol(numStr2);
    printf("%s to long integer: %ld\n", numStr2, num2);

    // No valid number at the start
    char numStr3[] = "abc123";
    long num3 = atol(numStr3);
    printf("%s to long integer: %ld\n", numStr3, num3);

    // Spaces then a number
    char numStr4[] = "   456789";
    long num4 = atol(numStr4);
    printf("'%s' to long integer: %ld\n", numStr4, num4);

    return 0;
}

Output

1234567890 to long integer: 1234567890
98765xyz to long integer: 98765
abc123 to long integer: 0
'   456789' to long integer: 456789

Explanation

1. numStr1 is a valid number string. atol() converts it to a long integer.

2. numStr2 has a number, then other characters. atol() stops at non-number characters.

3. numStr3 doesn't start with a number. atol() returns 0.

4. numStr4 has spaces, then a number. atol() skips the spaces and converts the number.

Remember, atol() stops converting at non-number characters and returns 0 if no number starts the string.


Comments