w3resource

C atol() function

C atol() function - Convert a string to a long integer

The atol() function is used to convert a character string to a long value.

Syntax:

long int atol(const char *str)

Parameters:

Name Description Required /Optional
str String to be converted. Required

Return value from atol()

  • Returns a long value.

Example: atol() function

The following example shows the usage of atol() function.


#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
 
int main(void)
{   
    char    *str = NULL;
    long    value = 0;
    // string value with leading and trailing white spaces.
    str = "  -7435 ";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // string value with an arbitrary decimal point.
    str = "732946.45";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // Another example with an overflow condition occurring.
    str = "234243820342342-422348";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );
    if (errno == ERANGE)
    {
       printf("Overflow condition occurred.\n");
    }
}

Output:

Function: atol( "  -7435 " ) = -7435
Function: atol( "732946.45" ) = 732946
Function: atol( "234243820342342-422348" ) = 598985798

C Programming Code Editor:

Previous C Programming: C atoi()
Next C Programming: C strtod()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdlib/c-atol.php