home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / learn / strtonum.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-10-06  |  1.2 KB  |  43 lines

  1. /* STRTONUM.C illustrates string to number conversion functions including:
  2.  *      strtod              strtol              strtoul
  3.  */
  4.  
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7.  
  8. main()
  9. {
  10.     char *string, *stopstring;
  11.     double x;
  12.     long l;
  13.     unsigned long ul;
  14.     int base;
  15.  
  16.     /* Convert string to double. */
  17.     string = "3.1415926INVALID";
  18.     x = strtod( string, &stopstring );
  19.     printf( "\nString: %s\n", string );
  20.     printf( "\tDouble:\t\t\t%f\n", x );
  21.     printf( "\tScan stopped at:\t%s\n", stopstring );
  22.  
  23.     /* Convert string to long using bases 2, 4, and 8. */
  24.     string = "-10110134932";
  25.     printf( "\nString: %s\n", string );
  26.     for( base = 2; base <= 8; base *= 2 )
  27.     {
  28.         l = strtol( string, &stopstring, base );
  29.         printf( "\tBase %d signed long:\t%ld\n", base, l );
  30.         printf( "\tScan stopped at:\t%s\n", stopstring );
  31.     }
  32.  
  33.     /* Convert string to unsigned long using bases 2, 4, and 8. */
  34.     string = "10110134932";
  35.     printf( "\nString: %s\n", string );
  36.     for( base = 2; base <= 8; base *= 2 )
  37.     {
  38.         ul = strtoul( string, &stopstring, base);
  39.         printf("\tBase %d unsigned long:\t%ld\n", base, ul );
  40.         printf("\tScan stopped at:\t%s\n", stopstring );
  41.     }
  42. }
  43.