将字符串转换为整型的函数

将字符串转换为整型的函数:

C/C++ code
 
    
int atoi( const char * str) { int sign = 0 ,num = 0 ; assert(NULL != str); while ( * str == ' ' ) { str ++ ; } if ( ' - ' == * str) { sign = 1 ; str ++ ; } while (( * str >= ' 0 ' ) && ( * str <= ' 9 ' )) { num = num * 10 + ( * str - ' 0 ' ); // 就是这一行,将对应字符转化为数字 str ++ ; } if (sign == 1 ) return - num; else return num; }

将字符串转换为浮点型的函数:
C/C++ code
 
    
double atof( const char * str) { double val = 0.0 ,power = 0.0 ; int sign = 0 ; assert(NULL != str); while ( * str == ' ' ) { str ++ ; } sign = ( * str == ' - ' ) ? - 1 : 1 ; if ( ' - ' == * str || ' + ' == * str) { str ++ ; } while (( * str >= ' 0 ' ) && ( * str <= ' 9 ' )) { val = val * 10.0 + ( * str - ' 0 ' ); str ++ ; } if ( ' . ' == * str) { str ++ ; } power = 1.0 ; while (( * str >= ' 0 ' ) && ( * str <= ' 9 ' )) { val = val * 10.0 + ( * str - ' 0 ' ); power *= 10 ; str ++ ; } return sign * val / power; }

你可能感兴趣的:(小应用)