C – Convert String to Int in C

How to Convert String to int in C Language?

Sometimes, a number is input as a string (char *). To use it for any mathematical operation, we have to convert the string to int in C / char * to int c. There are two ways to do this.

  1. The first method is to manually convert the string into an integer.
  2. The second method is to use the built-in functions.

So let’s try to fix these problems.

Manual Conversion / char * to int c

As we said before, to convert a string to a number, we need to know the ASCII table you can see it below:

C Function

Description of the function

  1. Check the validity of the string
  2. Check the sign
  3. The String to int in base 10 conversion loop
  4. Return the result, if the number is negative then change the sign of the number

C Program Example

The following example shows the usage of string2int() function. In this case, the function converts from string to int in indicated base.

String to int in C - manualy

Description of the program

The function char2decBase converts the char c to decimal number in base int numberBase.

The function string2int converts the char stringNumber[] to int number in base int numberBase (eg: decimal, binary, hexa). The base range is from 2 till 36.

Convert String to Int in C / char * to int c Using the atoi() Function

The atoi() is a function that converts the string argument str to an int.


Following is the prototype for atoi() function.


str – is of type pointer to a character and this is the string representation of an integral number.

Return Value

After execution this function returns an integer value. If no valid conversion could be performed, it returns 0 (zero). The atoi() function is present in the stdlib.h header file.


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

Output:String To Int in C atoi() function
I hope that this article has been helpful to you. Do try out the examples for yourself and experiment with them. Practice Makes More Perfect.

C (programming language) – Wikipedia, the free encyclopedia
C library function – atoi()

Leave a Reply

Your email address will not be published. Required fields are marked *