字符数组到单个整数

Array of chars to a single integer

本文关键字:整数 单个 数组 字符      更新时间:2023-10-16

我需要一些关于将字符转换为单个整数值的指导。我不应该使用任何转换它们的库函数。我理解如何使用char - '0' = int将单个字符转换为数组内的int,我的问题是,如果有一种方法可以将整数数组变为单个整数。我正在使用iostream, string和cctype。

谢谢

看一下这段代码:

#include <string.h>
#include <iostream>
int main(void) {
    char str[20] = {'1', '2', '3', '4', '5', '6', ''};  // char string;
    int i, len;
    long long number = 0;                                 // number which stores the value 
    len = strlen(str);                                    // calculate the length of string
    i = 0;
    for(i=0; i<len; i++) {
        number = 10*number + (str[i] - '0');
    }
    std::cout << number << std::endl;                     // number
    return 0;
}

注意:它可以处理从0到9,223,372,036,854,775,807的所有+ive值。我们甚至可以将它扩展到-ive值,只需检查字符串的第一个字符是否为负号(-)