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:

  1. STEP 1: Declare a recursive function ‘stringToNumber ‘with parameters (int arr[] , int len)
  2. STEP 2: Base Case: if (len == 0), convert the character into number and return it.
  3. STEP 3: Recursive Case: Convert the character into number and store it in variable a.
  4. 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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.