DEV Community

Lalit Kumar
Lalit Kumar

Posted on

Convert string to integer in C using strtol

In this post you are going to learn how to convert a string to an integer in C ; that is, convert one stringto one intor long; so that you can use it as an integer and not as a string.

title: "Convert string to integer in C using strtol"
tags: c

canonical_url: https://kodlogs.com/blog/2082/convert-string-to-integer-in-c-using-strtol

Table of contents:

  • Convert string to integer in C.
  • Complete example.

For the conversion we are going to use the strtol function . If you want to do the reverse process, please see how to convert a number to string in C.

Convert string to integer in C:

All we need is to invoke the function strtol; it will return a longthat could be converted to int. The simplest example is the following:

char * string = " 2052 " ;
int integer = ( int ) strtol (string, NULL , 10 );

The arguments that strtol takes are, in order:

  1. The string that we are going to convert
  2. A pointer that will point to the place where the string ended up doing the conversion, this is not necessary so we leave it in NULL.
  3. The base, which is base 10, decimal The function will return a longthat we convert to a int.

Complete example:

The code looks like this:

# Include  < stdio.h >
# Include  < stdlib.h >


int  main ( void ) {
    char * string = " 2052 " ;
    int integer = ( int ) strtol (string, NULL , 10 );
    printf ( " Integer: % d . Integer + 1: % d " , integer, integer + 1 );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)