C language library function name: atoi
Function: converts a string to an integer.
Source: ASCII to integer.
Prototype: int atoi (const char * nptr );
Function Description: nptr string. If the first non-space character exists, and if it is not a number or a plus or minus sign, zero is returned. Otherwise, type conversion is started, the conversion is stopped when a non-Numeric (including the terminator \ 0) character is detected. The integer number is returned.
Header file: # include <stdlib. h>
Program example:
1)
# Include <stdlib. h>
# Include <stdio. h>
Int main (void)
{
Int N;
Char * STR = "12345.67 ";
N = atoi (STR );
Printf ("string = % s integer = % d \ n", STR, N );
Return 0;
}
Execution result:
String = 12345.67 integer = 12345
2)
# Include <stdlib. h>
# Include <stdio. h>
Int main ()
{
Char A [] = "-100 ";
Char B [] = "123 ";
Int c;
C = atoi (a) + atoi (B );
Printf ("c = % d \ n", c );
Return 0;
}
Execution result:
C = 23
Simple implementation of atoi function source code:
# Include <cctype>
Int my_atoi (const char * p ){
Assert (p! = NULL );
Bool neg_flag = false; // symbol mark
Int res = 0; // result
If (p [0] = '+' | p [0] = '-')
Neg_flag = (* p ++! = '+ ');
While (isdigit (* p) res = res * 10 + (* p ++-'0 ');
Return neg_flag? 0-res: res;
}