user6719757 user6719757 - 3 months ago 5
C Question

how do i convert string like "12345" to int in c using recursion

If I got

char* "12345"
and I want to convert to
int
with a recursive function, how can I do that ?

This is a simple way how to convert
char
to
int
with loop.

while (str[i]) {
new_num *= 10;
new_num += str[i++] - '0';
}

Answer

Yet another variant without length calculation:

#include <stdio.h>
int convert_(char* s, int r) {
  return *s ? convert_(s + 1, r * 10 + (*s - '0')) : r;
}
int convert(char* s) {
  return convert_(s, 0);
}
void main()
{
  printf("%d", convert("123456"));
}
Comments