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:
- The string that we are going to convert
- 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.
- 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 );
}
Top comments (0)