我正在构建自己的字符串类,并尝试使用此函数将数字字符串转换为整数:
int String::convertToInt() const {
int exp = length() - 1;
int result = 0;
for(int i = 0; i < length(); ++i) {
result += (charAt(i) - '0') * (10 ^ exp);
--exp;
}
return result;
}
有些地方不对劲,但我无法确定是什么原因。当我尝试将“49”转换为 int 时,它会将其转换为 134。
最佳答案
^
是异或。我相信您正在寻找 std::pow(10, exp)
。
甚至这样:
int String::convertToInt() const {
int order = std::pow(10, length() - 1);
int result = 0;
for(int i = 0; i < length(); ++i) {
result += (charAt(i) - '0') * order;
order /= 10;
}
return result;
}
关于c++ - 当我不使用标准字符串时,如何在 C++ 中将字符串转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19727649/