将多数字字符数转换为整数

Converting multi-digit char number to int

本文关键字:整数 转换 数字字符      更新时间:2023-10-16

我正在尝试从用户输入一个数字(如12345)并将其转换为int。我使用的代码是:

int convertToNumber(char a[10]) {
    int output = 0;
    int b;
    int intArray[10];
    //Finds length
    for (int i = 0; a[i]!=0; i++) {
        if (a[i]==0) {
            b=i-1;
        }
    }
    //Runs through every letter.
    for (int i = 0; a[i]!=0; i++) {
        //Checks if user inputted anything but letter
        intArray[i] = a[i] - '0';
        //Multiplying it by the distance from the end
        intArray[i]= intArray[i] * (10^(b-i));
        //Adds to output
        output=+intArray[i];
    }
    return output;
}

然而,这并没有像我希望的那样结束。有人知道怎么了吗?

您需要介绍C++中的运算符。10^(b-i)不是(b-i)的10次方,而是10 XOR b-i。此外,为了找到长度,不要滚动自己的函数,使用std::strlen()

但无论如何,你不需要一个明确的长度:沿着字符串累积乘积。

int my_str2int(const char *s)
{
    int res = 0;
    while (*s) {
        res *= 10;
        res += *s++ - '0';
    }
    return res;
}

此外,我刚刚注意到标题:

我试图从用户那里输入一个数字(比如12345),并将其转换为int

如果这就是你想要的:

long l = std::strtol("12345", NULL, 0);
unsigned long ul = std::strtoul("12345", NULL, 0);
long long ll = std::strtoll("12345", NULL, 0);
unsigned long long ull = std::strtoull("12345", NULL, 0);
int i = std::atoi("12345");

和往常一样,医生们并不邪恶。

您可以尝试避免在这里重新发明轮子。查找strtoulstrtoull,查看它们在您的系统中是否可用。这些也处理不同基数的数字,如果字符串包含数字和非数字的混合物,则会为您提供指向第一个非数字的指针。

而且,正如其他人所指出的,^执行逐位XOR。

您希望在数学库中使用pow函数。^执行xor。