How to convert a string to integer in C?

后端 未结 12 1568
清酒与你
清酒与你 2020-11-22 01:40

I am trying to find out if there is an alternative way of converting string to integer in C.

I regularly pattern the following in my code.

char s[] =         


        
12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:01

    You can code atoi() for fun:

    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);
    }
    

    You can also make it recursive, which can fold in 3 lines. =)

提交回复
热议问题