2015-05-02 83 views
1

我尝试编写一个将字符串转换为整数(如atoi)的函数。我不明白为什么我的函数“convertir”不打印我的变量“res”,而“test 1”“test 2”...“test 4”被打印。我让你看看我的代码,如果你看到不好的东西请告诉我。C++ - 如何将char转换为int?

#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] != '\0'){ 
     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 != '\0'){ 
     c=s[j]; 
     printf("test %d \n", j); 
     res = res + (c - 48) * xpown(10,i); 
     i--; 
     j++; 
    } 
    printf("%d", res); 
} 
+0

不能使用''#在C++注释。那些应该是''''。 – Barmar

+0

好的,谢谢你,我编辑 – cryckx

+0

为了简单起见,你可以用'c''0'来代替'c-48'来得到一个数字,因为'0'是一个带有ASCII码48的'char'。这样,你的代码变得更可读。 – vsoftco

回答

0

你正在设置i太高。考虑最简单的情况,其中s有1个数字。您要将该位数乘以1(10 ),而不是10(10 )。因此,它应该是:

int i = lent(s) - 1; 

顺便说一句,你不应该硬编码值48,使用 '0':

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

标准函数atoi()可能会做你想要的。

+1

我想重写atoi,因为我学习C,而且我认为这是一个很好的练习 – cryckx

+0

他说他正在尝试写一个像atoi这样的函数。很显然,他有兴趣学习如何自己做。 – Barmar