String conversion function

C language provides several standard library functions, which can convert a string into a number of any type (integer, long integer, floating point, etc.). The following is an example of using the atoi() function to convert a string to an integer:

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, which is the string to be converted to a number. The return value of the atoi() function is the converted integer value.

The following functions can convert a string to a number:

函数名    作  用

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 double-precision floating point Value, and report all remaining numbers that cannot be converted
strtol() converts a string to a long integer value, and reports all remaining numbers that cannot be converted
strtoul() converts a string to an unsigned long integer value, and reports that it cannot All remaining numbers converted

Converting a string to a number may cause an overflow. If you use a function like strtoul(), you can check for this overflow error. Consider 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 above example, the string to be converted is too long and exceeds the value range of the unsigned long integer value. Therefore, the strtoul() function will return ULONG_MAX(4294967295) and use it. char leftover points to the part of the character string that caused the overflow; at the same time, the strtoul() function also assigns the global variable errno to ERANGE to notify the caller of the function that an overflow error has occurred. The functions strtod() and strtol() handle overflow errors in exactly the same way as the function strtoul(). You can learn more about the details of these three functions from the compiler documentation.

Guess you like

Origin blog.csdn.net/weixin_44856544/article/details/114942582