home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / learn / mkfpstr.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-12-02  |  1.4 KB  |  51 lines

  1. /* MKFPSTR.C illustrates building and displaying floating point strings
  2.  * without printf. Functions illustrated include:
  3.  *      strcat          strncat         cscanf          fcvt
  4.  */
  5.  
  6. #include <stdlib.h>
  7. #include <conio.h>
  8. #include <string.h>
  9.  
  10. main()
  11. {
  12.     int decimal, sign;
  13.     int precision = 7;
  14.     static char numbuf[50] = ""; 
  15.     char *pnumstr, tmpbuf[50];
  16.     double number1, number2;
  17.  
  18.     cputs( "Enter two floating point numbers: " );
  19.     cscanf( "%lf %lf", &number1, &number2 );
  20.     putch( '\n' );
  21.  
  22.     /* Use information from fcvt to format number string. */
  23.     pnumstr = fcvt( number1 + number2, precision, &decimal, &sign );
  24.  
  25.     /* Start with sign if negative. */
  26.     if( sign )
  27.         strcat( numbuf, "-" );
  28.  
  29.     if( decimal <= 0 )
  30.     {
  31.         /* If decimal is left of first digit (decimal negative), put
  32.          * in leading zeros, then add digits.
  33.          */
  34.         strcat( numbuf, "0." );
  35.         memset( tmpbuf, '0', (size_t)abs( decimal ) );
  36.         tmpbuf[abs( decimal )] = 0;
  37.         strcat( numbuf, tmpbuf );
  38.         strcat( numbuf, pnumstr );
  39.     }
  40.     else
  41.     {
  42.         /* If decimal is right of first digit, put in leading digits.
  43.          * then add decimal and trailing digits.
  44.          */
  45.         strncat( numbuf, pnumstr, (size_t)decimal );
  46.         strcat( numbuf, "." );
  47.         strcat( numbuf, pnumstr + decimal );
  48.     }
  49.     cputs( strcat( "Total is: ", numbuf ) );
  50. }
  51.