home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / file / scanf.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-11-01  |  2.0 KB  |  64 lines

  1. /* SCANF.C illustrates formatted input. Functions illustrated include:
  2.  *          scanf           fflush          flushall
  3.  *
  4.  * For other examples of formatted input, see TABLE.C (fscanf) and
  5.  * SETTIME.C (sscanf).
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <conio.h>
  10.  
  11. main()
  12. {
  13.     int result, integer;
  14.     float fp;
  15.     char string[81];
  16.  
  17.     /* Get numbers. */
  18.     printf( "Enter an integer and a floating point number: " );
  19.     scanf( "%d %f", &integer, &fp );
  20.     printf( "%d + %f = %f\n\n", integer, fp, integer + fp );
  21.  
  22.     /* Read each word as a string. */
  23.     printf( "Enter a sentence of four words with scanf: " );
  24.     for( integer = 0; integer < 4; integer++ )
  25.     {
  26.         scanf( "%s", string );
  27.         printf( "%s\n", string );
  28.     }
  29.  
  30.     /* Clear the input buffer and get with gets. */
  31.     fflush( stdin );
  32.     printf( "Enter the same sentence with gets: " );
  33.     gets( string );
  34.     printf( "%s\n", string );
  35.  
  36.     /* Specify delimiters. The ^ inside the brackets says accept any
  37.      * character except the following other characters in brackets (tab
  38.      * and newline in the example).
  39.      */
  40.     printf( "Enter the same sentence with scanf and delimiters: " );
  41.     scanf( "%[^\n\t]s", string );
  42.     printf( "%s\n", string );
  43.  
  44.     /* Loop until input value is 0. */
  45.     printf( "\n\nEnter numbers in C decimal (num), hex (0xnum), " );
  46.     printf( "or octal (0num) format.\nEnter 0 to quit\n\n" );
  47.     do
  48.     {
  49.         printf( "Enter number: " );
  50.         result = scanf( "%i", &integer );
  51.         if( result )
  52.             /* Display valid integers. */
  53.             printf( "Decimal: %i  Octal: 0%o  Hexadecimal: 0x%X\n\n",
  54.                     integer, integer, integer );
  55.         else
  56.         {   /* Read invalid characters. Then flush and continue. */
  57.             scanf( "%s", string );
  58.             printf( "Invalid number: %s\n\n", string );
  59.             flushall();
  60.             integer = 1;
  61.         }
  62.     } while( integer );
  63. }
  64.