C 语言实现字符串和整数的相互转化

下面用 C 语言实现字符串和整数的相互转化

一、字符串转化为整数

int str_to_num(const char* s)  // 字符串转化为整数
{
    int exp=0, n=0;
    const char *h = s;
    const char *t = NULL;
    for(;*h <'0' || *h >'9'; h++)  // 找到第一位数字
        ;
    for(t=h; *t >='0' && *t <='9'; ++t)  // 找到最后一位数字
        ;
    t--;
    while(t >= h)
    {
        n += (*t - 48)*power(10, exp);
        t--;
        exp++;
    }
    return n;
}

二、整数转化为字符串

void num_to_str(const int num, char str[33])  // 整数转化为字符串
{
    int dividend = num;
    int i = 0;
    int j = 0;
    int temp = 0;
    while(dividend)
    {
        str[j] = (dividend%10)+'0';
        dividend /= 10;
        j++;
    }
    str[j] = '\0';
    j--;
    while(i<j)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++;
        j--;
    }
    //printf("%s\n", str);
}

猜你喜欢

转载自blog.csdn.net/yueyinlizun/article/details/79893536