c++ - 如何将 char 转换为 int?

c++ - how to convert char to int?

我尝试编写一个将字符串转换为整数的函数(如 atoi)。我不明白为什么我的函数 "convertir" 不打印我的变量 "res " 而 "test 1 " "test 2"... "test 4" 被打印。我让你看看我的代码,如果你看到什么不好的地方请告诉我。

#include "stdio.h"
#include "stdlib.h"
int xpown(int x, int n); // x^n
int lent(char str[]); // return length of string
int convertir(char s[]); //convert char to int
int main(){
    char s[] ="1234";
    convertir(s);
    return 0;
}

int xpown(int x, int n){
    int res = 1;
    while (n != 1){
        res= res*x;
        n--;
    }
    return res;
}

int lent(char str[]){
    int res =0;
    int i=0;
    while (str[i] != '[=10=]'){
        res=res+1;
        i++;
    }
    return res;
}

int convertir(char s[]){
    int res = 0;
    int i = lent(s);
    int j = 0;
    char c = s[j];
    while (c != '[=10=]'){
        c=s[j];
        printf("test %d \n", j);
        res = res + (c - 48) * xpown(10,i);
        i--;
        j++;
    }
    printf("%d", res);
}

标准函数 atoi() 可能会执行您想要的操作。

i 设置得太高了。考虑最简单的情况,其中 s 有 1 个数字。您希望将该数字乘以 1 (100),而不是 10 (101)。所以应该是:

int i = lent(s) - 1;

顺便说一句,您不应该对值 48 进行硬编码,使用 '0':

res += (c - '0') * xpown(10, i);