how can I convert character to integer number

前端 未结 4 956
小蘑菇
小蘑菇 2021-01-07 17:15

How could I change an array of character (string) to an integer number without using any ready function (ex atoi();) for example :-

 char a[5]=\'4534\';


        
相关标签:
4条回答
  • 2021-01-07 17:55

    You can go like this

    It's working

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    
    int main()
    {
    
      char a[5] = "4534";
    
      int converted = 0;
    
      int arraysize = strlen(a);
    
      int i = 0;
      for (i = 0; i < arraysize ; i++)
      {
        converted = converted *10 + a[i] - '0';
      }
    
      printf("converted= %d", converted);   
    
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-07 18:07

    Without using any existing libraries, you have to:

    1. Convert character to numeric digit.
    2. Combine digits to form a number.

    Converting character to digit:

    digit = character - '0';
    

    Forming a number:

    number = 0;
    Loop:
    number = number * 10 + digit;
    

    Your function will have to check for '+' and '-' and other non-digits characters.

    0 讨论(0)
  • 2021-01-07 18:13

    First of all this statement

     char a[5]='4534';
    

    will not compile. I think you mean

     char a[5]="4534";
               ^^   ^^
    

    To convert this string to a number is enough simple.

    For example

    int number = 0;
    
    for ( const char *p = a; *p >= '0' && *p <= '9'; ++p )
    {
        number = 10 * number + *p - '0';
    }
    

    Or you could skip leading white spaces.

    For example

    int number = 0;
    
    const char *p = s;
    
    while ( std::isspace( ( unsigned char )*p ) ) ++p;
    
    for ( ; *p >= '0' && *p <= '9'; ++p )
    {
        number = 10 * number + *p - '0';
    }
    

    If the string may contain sign '+' or '-' then you can check at first whether the first character is a sign.

    0 讨论(0)
  • 2021-01-07 18:19

    I prefer to use the std::atoi() function to convert string into a number data type. In your example you have an non-zero terminated array "\0", so the function will not work with this code.

    Consider to use zero terminated "strings", like:

    char *a = "4534";
    
    int mynumber = std::atoi( a );   // mynumber = 4534
    
    0 讨论(0)
提交回复
热议问题