how can I convert character to integer number

前端 未结 4 955
小蘑菇
小蘑菇 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 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.

提交回复
热议问题