Computers in Engineering WWW Site - Example 10.2

Example 10.2


C Version

/*
   Introduction to accessing data.
*/

#include <stdio.h>

#define  false  0
#define  true   1

main()
{

/*  Declaration statements  */

  short age=0, pds=0, single_tmp=0;
  double days, grams;
  char name[16], adrs[24] , check;
  int single;    /*  Really logical/boolean   */
  char *TEMP;
  clrscr();
 printf("C22.C -> This program provides examples of how to read in data.\n");

 do
 {
    printf("\nEnter Age    :");
    scanf("%hd", &age);
    printf("\nEnter weight in pounds    :");
    scanf("%hd", &pds);
    printf("\nEnter Name   :");
    getchar();
    fgets(name, 16, stdin);
    TEMP = strchr(name, '\n');   /*  To get rid of the \n at    */
    if (TEMP != NULL) {          /*  the end of the "name"      */
      *TEMP = 0;                 /*  which can produce format   */
      ungetc('\n', stdin);       /*  errors when printing data  */
    }
    printf("\nEnter Address:");
    getchar();
    fgets(adrs, 24, stdin);
    TEMP = strchr(adrs, '\n');
    if (TEMP != NULL)
      *TEMP = 0;
    /*
    Since we cannot read in a boolean from the keyboard
    we read an integer 1 or 0 and convert to boolean.
    */
    printf("\nSingle? (0/1) : ");
    scanf("%hd", &single_tmp);    /*  Get 1 or 0 from user  */
    getchar();
    if (single_tmp == 0)          /*  Depending on user's   */
      single = false;             /*  entry, single will    */
    if (single_tmp == 1)          /*  take the value true   */
      single = true;              /*  or false.             */

    /*  Assignment statements  */

    grams = pds * 454.0;
    days = age * 365.25;

    /*  Print data  */

    printf("Name   : %s\nAddress: %s\n", name, adrs);
    printf("Age    : %d\nDays   : %8.2f\n", age, days);
    printf("PDS    : %d\nGRAMS  : %7.1f\n", pds, grams);
    printf("Single : ");
    puts(single ? " TRUE" : "FALSE");
    printf("Do you want to continue ? (y/n) :\t");
    check=getchar();
    check=toupper(check);   /*  Capital letter conversion  */
    clrscr();   /*  Clear screen before new entry  */

 }while(check != 'N');   /*  End of while loop if check != 'N'  */

  return(0);
}
/*  End of Program C22  */
/*
INPUT :
56
160
Baldy
22 Acacia Ave.

OUTPUT :
C22.C -> This program provides examples of how to read in data.

Enter Age    : 56

Enter PDS    : 160

Enter Name   : Baldy

Enter Address: 22 Acacia Ave.

Single? (0/1) : n
Name   : Baldy
Address: 22 Acacia Ave.
Age    : 56
Days   : 20454.00
PDS    : 160
GRAMS  : 72640.0
Single : FALSE
Do you want to continue ? (y/n) :n

*/

Last modified: 21/07/97