【问题标题】:c++ - how to convert char to int?c++ - 如何将char转换为int?
【发布时间】:2015-07-11 21:14:00
【问题描述】:

我尝试编写一个将字符串转换为整数的函数(如 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] != '\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++ 中将 # 用于 cmets。那些应该是//
  • 好的,谢谢,我编辑
  • 为简单起见,您可以使用c - '0' 而不是c - 48 来获取一个数字,因为0 是一个char,ASCII 码为48。这样,您的代码会变得多一点可读。
  • 我不知道谢谢!

标签: char int printf


【解决方案1】:

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

int i = lent(s) - 1;

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我想重写atoi,因为我学习C,我认为这是一个很好的练习
    • 他说他正在尝试编写像atoi 这样的函数。所以很明显他有兴趣学习如何自己做。
    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 2015-12-18
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    相关资源
    最近更新 更多