我尝试编写一个将字符串转换为整数(如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);
}
不能使用''#在C++注释。那些应该是''''。 – Barmar
好的,谢谢你,我编辑 – cryckx
为了简单起见,你可以用'c''0'来代替'c-48'来得到一个数字,因为'0'是一个带有ASCII码48的'char'。这样,你的代码变得更可读。 – vsoftco