This article describes the C language implementation of the method of converting strings to numbers. Share to everyone for your reference. The implementation methods are as follows:
The C language provides several standard library functions that can convert strings to numbers of any type (integer, long, floating-point, etc.). The following is an example of converting a string to an integer using the Atoi () function:
Copy Code code as follows:
# 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 argument, the string to convert to a number. The return value of the atoi () function is the integer value that is derived from the conversion.
The following functions can convert a string to a number:
------------------------------------------------------------------------
Function name function
------------------------------------------------------------------------
Atof () Converts a string to a double-precision floating-point value
Atoi () Converts a string to an integer value
ATOL () Converts a string to a long integer value
Strtod () Converts a string to a double-precision floating-point value and reports all remaining digits that cannot be converted
Strtol () Converts a string to a long integer value and reports all remaining digits that cannot be converted
Strtoul () Converts a string to an unsigned long integer value and reports all remaining digits that cannot be converted
------------------------------------------------------------------------
Converting a string to a number can cause an overflow, and if you are using a function such as Strtoul (), you can check for this overflow error. Take a look at the following example:
Copy Code code as follows:
# 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 example above, the string to be converted is too long to exceed the value range of the unsigned long integer value, so the Strtoul () function returns Ulong_max (4294967295) and causes the. The char leftover points to the part of the character in the string that caused the overflow, and the Strtoul () function also assigns the global variable errno to Erange to notify the caller of the function that an overflow error has occurred. Functions Strtod () and strtol () handle overflow errors in exactly the same way as function Strtoul (), and you can learn more about the details of these three functions from the compiler documentation.
I hope this article will help you with the C language program.