作为一个更大程序的一部分,我必须将一串数字转换为一个整数(最终是一个 float )。不幸的是,我不允许使用转换或 atoi。
我想到了一个简单的操作:
void power10combiner(string deciValue){
int result;
int MaxIndex=strlen(deciValue);
for(int i=0; MaxIndex>i;i++)
{
result+=(deciValue[i] * 10**(MaxIndex-i));
}
}
会起作用。如何将 char 转换为 int?我想我可以使用 ASCII 转换,但无论如何我都无法将字符添加到整数(假设转换方法有一个巨大的 if 语句,它返回每个 ASCII 数字后面的不同数值)。
最佳答案
有很多方法可以做到这一点,并且可以对您的函数进行一些优化和更正。
1) 您没有从函数返回任何值,因此返回类型现在是 int。
2) 您可以通过传递常量引用来优化此函数。
现在开始举例。
使用 std::stringstream进行转换。
int power10combiner(const string& deciValue)
{
int result;
std::stringstream ss;
ss << deciValue.c_str();
ss >> result;
return result;
}
不使用 std::stringstream 进行转换。
int power10combiner(const string& deciValue)
{
int result = 0;
for (int pos = 0; deciValue[pos] != '\0'; pos++)
result = result*10 + (deciValue[pos] - '0');
return result;
}
关于c++ - 将一串数字转换为任何形式的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059056/