将多数字字符数转换为整数
Converting multi-digit char number to int
我正在尝试从用户输入一个数字(如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");
和往常一样,医生们并不邪恶。
您可以尝试避免在这里重新发明轮子。查找strtoul
和strtoull
,查看它们在您的系统中是否可用。这些也处理不同基数的数字,如果字符串包含数字和非数字的混合物,则会为您提供指向第一个非数字的指针。
而且,正如其他人所指出的,^
执行逐位XOR。
您希望在数学库中使用pow函数。^执行xor。
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 如何在C++中将整数转换为其数字数组
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 将最小值整数转换为无符号长整型
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将74位整数转换为以31为底的整数
- 独立于实现的浮点/整数转换
- 以最少的步骤将给定整数转换为另一个整数
- 浮点到整数转换出错(即使浮点数已经是整数)
- 了解双精度转换与整数转换中的整数与截断关系
- 禁止具有精度损失的整数转换
- 将任意整数转换为 void*
- 将 32 位大端有符号整数转换为有符号小端整数
- char a[0] 使用 itoa() 将整数转换为字符串的目的
- 使用函数时从整数转换为字符串
- 尝试从整数转换为字符串的月份
- 如何在C++中将整数转换为字节,以便 Unity 在通过 UDP 传输后能够理解它们
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 如何避免字符串到整数转换情况下的无效参数异常