converting char to int, recursively

closed account (NCRLwA7f)
Hello,
I have the following code to convert a character representation of a number to an integer number. The problem that I am having is breaking out the loop and I need a better way to increment the array.

so for example, if I have the number "23456" I will need to convert it to an integer value of 23456

In the following loop, i gets reassigned to 0 every time the function call itself.
Also, I'm not sure if my condition of reaching a null is even being reached.

1
2
3
4
5
6
7
8
9
  void ascii_to_int(string number){
	int i = 0;
	if(number[i] != '\0'){
		cout << (number[i] - '0');
		}
	
	ascii_to_int(&number[i+1]);
	return;
}
Last edited on
Why not just use stoi() instead of rolling your own?

closed account (NCRLwA7f)
yes, that is very true and far more effective. The problem is that I need to know how to do this for an assignment.
Is recursion required?

This can easily be done with iteration.
closed account (NCRLwA7f)
Yes recursion was required but i ended up figuring it out. I just passed the string which is just a char array as a pointer and just bumped the address every loop.
Thanks anyway.
Topic archived. No new replies allowed.