我试图找出是否有一种在C中转换字符串为整数的替代方法。

在我的代码中,我经常使用以下模式。

char s[] = "45";

int num = atoi(s);

那么,有没有更好的办法呢?


当前回答

不要使用来自ato…组。这些都坏了,几乎毫无用处。一个稍好的解决方案是使用sscanf,尽管它也不是完美的。

将字符串转换为整数,函数from strto…应该使用Group。在你的具体情况下,它将是strotol函数。

其他回答

你可以编写atoi()来取乐:

int my_getnbr(char *str)
{
  int result;
  int puiss;

  result = 0;
  puiss = 1;
  while (('-' == (*str)) || ((*str) == '+'))
  {
      if (*str == '-')
        puiss = puiss * -1;
      str++;
  }
  while ((*str >= '0') && (*str <= '9'))
  {
      result = (result * 10) + ((*str) - '0');
      str++;
  }
  return (result * puiss);
}

你也可以让它成为递归的,它可以折叠成3行。

int atoi(const char* str){
    int num = 0;
    int i = 0;
    bool isNegetive = false;
    if(str[i] == '-'){
        isNegetive = true;
        i++;
    }
    while (str[i] && (str[i] >= '0' && str[i] <= '9')){
        num = num * 10 + (str[i] - '0');
        i++;
    }
    if(isNegetive) num = -1 * num;
    return num;
}

是的,你可以直接存储整数:

int num = 45;

如果你必须解析一个字符串,atoi或strol将赢得“最短代码量”的比赛。

在c++中,你可以使用这样一个函数:

template <typename T>
T to(const std::string & s)
{
    std::istringstream stm(s);
    T result;
    stm >> result;

    if(stm.tellg() != s.size())
        throw error;

    return result;
}

这可以帮助您将任何字符串转换为任何类型,如float, int, double…

这个函数会帮助你

int strtoint_n(char* str, int n)
{
    int sign = 1;
    int place = 1;
    int ret = 0;

    int i;
    for (i = n-1; i >= 0; i--, place *= 10)
    {
        int c = str[i];
        switch (c)
        {
            case '-':
                if (i == 0) sign = -1;
                else return -1;
                break;
            default:
                if (c >= '0' && c <= '9')   ret += (c - '0') * place;
                else return -1;
        }
    }

    return sign * ret;
}

int strtoint(char* str)
{
    char* temp = str;
    int n = 0;
    while (*temp != '\0')
    {
        n++;
        temp++;
    }
    return strtoint_n(str, n);
}

裁判:http://amscata.blogspot.com/2013/09/strnumstr - - 2.版本的html