C implements the method of converting a string to a number

  • 2020-04-02 02:58:47
  • OfStack

This article illustrates the C language implementation of a string into a number method. Share with you for your reference. The specific implementation method is as follows:

The C language provides several standard library functions that can convert strings to Numbers of any type (integer, long integer, floating point, and so on). Here 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 takes only one argument, the string to be converted to a number. The return value of the atoi() function is the integer value of the transformation.    

The following functions convert a string to a number:
------------------------------------------------------------------------
      The function name       As a   with
------------------------------------------------------------------------
  The atof ()         Converts a string to a double - precision floating - point value
  The 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 Numbers 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
------------------------------------------------------------------------  
 
If you use a function like strtoul(), you can check for overflow errors that can occur when converting a string to a number. 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: %sn",str);
    printf("Converted number: %1un" , num);
    printf("Leftover characters: %sn" , leftover);
}

In the above example, the string to be converted is too long for the unsigned long integer value, so the strtoul() function returns ULONG_MAX(4294967295) and makes. Char leftover points to the part of the string that caused the overflow. The strtoul() function also assigns the global variable errno to ERANGE to notify the caller of the overflow error. The functions strtod() and strtol() handle overflow errors in exactly the same way as the function strtoul(), and you can learn more about these functions in the compiler documentation.

Hope that the article described in the C programming language for you to help.


Related articles: