将一串数字转换为任何形式的整数

Converting a string of numbers to any form of an int

本文关键字:任何形 整数 转换 数字 一串      更新时间:2023-10-16

作为更大程序的一部分,我必须将一串数字转换为整数(最终是浮点数)。不幸的是,我不允许使用铸造或 atoi。

我想一个简单的操作是这样的:

void power10combiner(string deciValue){
   int result;
   int MaxIndex=strlen(deciValue);
        for(int i=0; MaxIndex>i;i++)
        {
          result+=(deciValue[i] * 10**(MaxIndex-i));
        }       
}

会工作。如何将字符转换为整数?我想我可以使用 ASCII 转换,但无论如何我都无法将字符添加到整数中(假设转换方法是有一个巨大的 if 语句,该语句返回每个 ASCII 数字后面的不同数值)。

有很多

方法可以做到这一点,并且可以对函数进行一些优化和更正。

1)你没有从函数返回任何值,所以返回类型现在是int。

2) 您可以通过传递 const 引用来优化此功能。

现在来看例子。

使用 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] != ''; pos++)
        result = result*10 + (deciValue[pos] - '0');
    return result;
}

由 suggestion 编辑,并添加了一些解释。

int base = 1;
int len = strlen(deciValue);
int result = 0;
for (int i = (len-1); i >= 0; i--) { // Loop right to left. Is this off by one? Too tired to check.
    result += (int(deciValue[i] - '0') * base); // '0' means "where 0 is" in the character set. We are doing the conversion int() because it will try to multiply it as a character value otherwise; we must cast it to int.
    base *= 10; // This raises the base...it's exponential but simple and uses no outside means
}

这假设字符串只是数字。如果您需要更多说明,请发表评论。

您可以通过简单地实现任何数字基数的位值系统,将字符串迭代解析为整数。假设您的字符串以 null 结尾且数字无符号:

unsigned int parse(const char * s, unsigned int base)
{
    unsigned int result = 0;
    for ( ; *s; ++s)
    {
        result *= base;
        result += *s - '0'; // see note
    }
    return result;
}

如前所述,这仅适用于使用数字 0、...、9 的最多 10 个基数,这些数字保证在执行字符集中按顺序排列。如果您需要更大的数字基数或更自由的符号集,则需要将指示行中的*s - '0'替换为确定输入字符数字值的合适查找机制。

我会使用

std::stringstream,但还没有人发布使用 strtol 的解决方案,所以这里有一个。请注意,它不执行处理超出范围的错误。在 unix/linux 上,您可以使用errno变量来检测此类错误(通过将其与 ERANGE 进行比较)。

顺便说一句,有用于浮点数的strtod/strtof/strtelld函数。

#include <iostream>
#include <cstdlib>
#include <string> 

int power10combiner(const std::string& deciValue){
   const char* str = deciValue.c_str();
   char* end; // the pointer to the first incorrect character if there is such
   // strtol/strtoll accept the desired base as their third argument
   long int res = strtol(str, &end, 10);
   if (deciValue.empty() || *end != '') {
       // handle error somehow, for example by throwing an exception
   }
   return res;
}
int main()
{
    std::string s = "100";
    std::cout << power10combiner(s) << std::endl;
}
相关文章: