c++ - 将一串数字转换为任何形式的 int

标签 c++ types type-conversion

作为一个更大程序的一部分,我必须将一串数字转换为一个整数(最终是一个 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/

相关文章:

node.js - socket.io Typescript 无法创建服务器, "This expression is not callable"

java - 如何将 oracle 数据类型映射到 java 数据类型?

c - 可能将 void* 转换为 unsigned long int 导致未定义的行为,即使 sizeof(void*)==sizeof(unsigned long int)

c++ - 在 C++ 中将临时变量作为非常量引用传递

c++ - 支持多种像素格式

c++ - 将数学符号存储到字符串C++中

scala - 函数式面向对象语言的类型系统

c++ - std::unique 并从对象容器中删除重复项

映射中的 Haskell 错误

polymorphism - SML中不使用数据类型的多态加法函数