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.
#include <stdio.h> int main() { char str[] = "12345"; int x; sscanf(str, "%d", &x); printf("%d", x); return 0; }
Output
12345
Using atoi()
It is another inbuilt function that can directly convert string to integer.
#include <stdio.h> #include <stdlib.h> int main() { char str[] = "12345"; int x; x = atoi(str); printf("%d", x); return 0; }
Using Manual Method
Here we will use our own custom logic for conversion.
#include <stdio.h> int main() { char str[] = "12345"; int x = 0, i; for(i = 0; str[i] != '\0'; ++i) x = x * 10 + (str[i] - '0'); printf("%d", x); return 0; }
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.