Example 1 (scanf -- Read Data)

This example scans various types of data.

#include <stdio.h>
int main(void)
{
   int i;
   float fp;
   char c, s[81];
   printf("Enter an integer, a real number, a character "
          "and a string : \n");
   if (scanf("%d %f %c %s", &i, &fp, &c, s) != 4)
      printf("Not all fields were assigned\n");
   else
   {
      printf("integer = %d\n", i);
      printf("real number = %f\n", fp);
      printf("character = %c\n", c);
      printf("string = %s\n",s);
   }
   return 0;
   /**************************************************************
      The output file should be similar to:
      Enter an integer, a real number, a character and a string:
      12 2.5 a yes
      integer = 12
      real number = 2.500000
      character = a
      string = yes
   **************************************************************/
}

Example 2 (scanf -- Read Data)

This example converts a hexadecimal integer to a decimal integer. The while loop ends if the input value is not a hexadecimal integer.

#include <stdio.h>
int main(void)
{
   int number;
   printf("Enter a hexadecimal number or anything else to quit:\n");
   while (scanf("%x",&number))
   {
      printf("Hexadecimal Number = %x\n",number);
      printf("Decimal Number     = %d\n",number);
   }
   return 0;
   /***************************************************************
      The output file should be similar to:
      Enter a hexadecimal number or anything else to quit:
      0x231
      Hexadecimal number = 231
      Decimal number = 561
      0xf5e
      Hexadecimal number = f5e
      Decimal number = 3934
      0x1
      Hexadecimal number = 1
      Decimal number = 1
      q
  *****************************************************************/
}