Implementation of the database function atoi () and the implementation of the database function atoi
Int atoi (const char * nptr );
IfThe first non-space characterYes. If it is a number or plus or minus sign, type conversion is started. If it is detected that the conversion is not a number (including the terminator \ 0), the conversion is stopped and the integer number is returned. Otherwise, zero is returned.
Note: If the string is illegal input: the string is null, and only one '+' or '-', non-number, and so on, returns the integer 0; if the input value is "0", the return value is the integer value 0. In this case, atoi () is distinguished by a global variable. Another point: for example, if the input is "123abc", atoi () can also be correctly executed and the number of integer values is 123.
Enum Status {kValid = 0, kInvalid}; int g_nStatus = kValid; int StrToInt (const char * str) {g_nStatus = kInvalid; long num = 0; if (str! = NULL & * str! = '\ 0') {bool minus = false; if (* str =' + ') str ++; else if (* str = '-') {str ++; minus = true;} if (* str! = '\ 0') {num = StrToIntCore (str, minus) ;}} return (int) num;} long StrToIntCore (const char * digits, bool minus) {long num = 0; const char * digit = digits; while (* digit! = '\ 0') {if (* digit> = '0' & * digit <= '9') {int flag = minus? -1: 1; num = num * 10 + flag * (* digit-'0'); if ((! Minus & num> 0x7FFFFFFF) | (minus & num <(signed int) 0x80000000) // check whether overflow exists {num = 0; break ;} digit ++;} else {// num = 0; break ;}} if (* digit = '\ 0' | digit-digits> 0) {g_nStatus = kValid;} return num ;}
Refer to offoffer
Int atoi (char * s) without C/C ++ library functions)
Int Atoi (char * s) {int Int = 0, I; for (I = 0; * (s + I )! = '\ 0'; I ++) {if (* (s + I) <'0' | * (s + I)> '9') return Int; int = Int * 10 + (* (s + I)-'0');} return Int;
}
Int atoi (char * s) without C/C ++ library functions)
# Include <stdio. h>
# Include <string. h>
Int atoi (char * s)
{
Int I, j, k, len, value = 0;
Int flag = 1;
Len = strlen (s );
J = 0;
For (I = 0; I <len; I ++)
{
If (s [I]! = ''& S [I]! = '\ T ')
{
S [j] = s [I];
J = j + 1;
}
}
S [j] = '\ 0 ';
If (j = 0) return 0;
K = 0;
If (s [0] = '-')
{
Flag =-1;
K = 1;
}
Else if (s [0] = '+ ')
{
Flag = 1;
K = 1;
}
For (I = k; I <j; I ++)
{
Value = value * 10 + s [I]-'0 ';
}
Value = flag * value;
Return value;
}
Void main ()
{
Char s [10] = "-12345 ";
Int n;
N = atoi (s );
Printf ("% d \ n", n );
}