Home »
C++ programs
C++ program to convert a string of number to integer
Here, we are going to learn how to convert a string to integer using C++ program?
Submitted by Indrajeet Das, on December 14, 2018
Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer.
Input format: Numeric string (string, Eg. "1234")
Output format: Corresponding integer (int, Eg. 1234)
Sample Input 1: "1231"
Sample Output 1: 1231
Sample Input 1: "12567"
Sample Output 1: 12567
Explanation:
In this question, we can solve it recursively. We start from unit’s digit and recursively shift to the last digit. After that we keeping on multiplying it by 10 and adding the number of present digit and return it. On completing the recursion it will return the number in integers.
Algorithm:
- STEP 1: Declare a recursive function ‘stringToNumber ‘with parameters (int arr[] , int len)
- STEP 2: Base Case: if (len == 0), convert the character into number and return it.
- STEP 3: Recursive Case: Convert the character into number and store it in variable a.
- STEP 4: return a + 10 *stringToNumber(arr, len -1)
Example:
Input = "23"
First Traversal = 2,
Second Traversal = 20 + 3,
Result = 23
C++ program:
#include <bits/stdc++.h>
using namespace std;
//To find length of the string
int length(char input[]){
int len = 0;
for(int i =0;input[i] != '\0';i++){
len++;
}
return len;
}
//Helper Function
int stringToNumber(char input[], int last){
//Base Case
if(last == 0){
return input[last] - '0';
}
//Recursive Call
int smallAns = stringToNumber(input,last-1);
int a = input[last] - '0';
return smallAns * 10 + a;
}
//Recursive Function
int stringToNumber(char input[]){
int len = length(input);
return stringToNumber(input,len-1);
}
int main(){
char input[50];
cout<<"Enter Input"<<endl;
cin>>input;
cout<<"The output/number is ";
cout<<stringToNumber(input)<<endl;
return 0;
}
Output
Enter Input
1234
The output/number is 1234