The C language converts a string to a number.
The C language provides several standard library functions that can convert strings into numbers of any type (integer, long integer, floating point type, etc. The following is an example of converting a string to an integer using the atoi () function:
# Include <stdio. h>
# Include <stdlib. h>
Void main (void );
Void main (void)
{
Int num;
Char * str = "100 ";
Num = atoi (str );
Printf ("The string 'str' is % s and the number 'num' is % d. \ n ",
Str, num );
}
The atoi () function has only one parameter, that is, the string to be converted to a number. The Return Value of the atoi () function is the integer value obtained by the conversion.
The following functions can convert strings to numbers:
------------------------------------------------------------------------
Function Name
------------------------------------------------------------------------
Atof () converts a string to a double-precision floating point value.
Atoi () converts a string to an integer.
Atol () converts a string to a long integer.
Strtodd () converts a string to a double-precision floating-point value and reports all the remaining numbers that cannot be converted
Strtol () converts a string to a long integer and reports all the remaining numbers that cannot be converted.
Strtoul () converts a string to an unsigned long integer value and reports all remaining numbers that cannot be converted
------------------------------------------------------------------------
Converting a string to a number may cause overflow. If you are using a function such as strtoul (), you can check this overflow error. See the following example:
# Include <stdio. h>
# Include <stdlib. h>
# Include <limits. h>
Void main (void );
Void main (void)
{
Char * str = "1234567891011121314151617181920 ";
Unsigned long num;
Char * leftover;
Num = strtoul (str, & leftover, 10 );
Printf ("Original string: % s \ n", str );
Printf ("Converted number: % 1u \ n", num );
Printf ("Leftover characters: % s \ n", leftover );
}
In the preceding example, the string to be converted is too long and exceeds the value range of the unsigned long integer. Therefore, the strtoul () function returns ULONG_MAX (4294967295) and enables the conversion. Char leftover points to the character that causes overflow in the string. At the same time, the strtoul () function also assigns the global variable errno to ERANGE to notify the function caller of an overflow error. The methods used to handle overflow errors by strtol () and strtol () functions are the same as those of strtoul (). You can learn more about these three functions in the Compilation Program documentation.