How to Convert String to int in C and C++

There are different ways to convert string to int in C and C++. Like using inbuilt function or writing custom code. Lets take a look on each of them one by one.

The programs below are written in C but the same concept will work for C++.

Ways to Convert String to int in C and C++

Using sscanf()

This function reads input directly from string. Take below example.

Output

12345

Using atoi()

It is another inbuilt function that can directly convert string to integer.

Using Manual Method

Here we will use our own custom logic for conversion.

In this method we are simply subtracting ASCII value of character zero from each character of string to obtain the integer.

For example in above case first character of string is 1. ASCII value of 1 and 0 are 49 and 48. The difference between these two values is 1 (49 – 48), that is the integer equivalent to character.

Comment below if you have queries or know any other way to convert string to number in C.

Leave a Comment

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