我如何使用递归将像"12345"这样的字符串转换为c中的int

-1 c recursion

如果我得到char* "12345"并且我想转换为int具有递归功能,我该怎么做?

这是一种如何转换charint循环的简单方法.

while (str[i]) {
    new_num *= 10;
    new_num += str[i++] - '0';
}
Run Code Online (Sandbox Code Playgroud)

use*_*559 5

如果"rexrsia/rxursia方式"意味着递归方式,这里有一种方法:

#include <stdio.h>
#include <string.h>

int convert_with_length(char* sz, int cch) {
    // base case: empty string
    if (cch == 0) {
        return 0;
    }

    // recursive case, use the last digit and recurse on the rest:
    // e.g. "12345" becomes 10 * convert("1234") + 5
    return (sz[cch - 1] - '0') + (10 * convert_with_length(sz, cch - 1));
}

int convert(char *sz) {
    return convert_with_length(sz, strlen(sz));
}

int main() {
    char* str = "12345";
    printf("result = %d\n", convert(str));
}
Run Code Online (Sandbox Code Playgroud)