home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap11 / card2.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-04-06  |  2.2 KB  |  87 lines

  1. /* card2.c --  demonstrates structure assignment and   */
  2. /*             how to pass a structure to a function   */
  3.  
  4. #include <stdio.h>      /* for NULL  and stdin */
  5. #include <string.h>     /* for strdup()        */
  6.  
  7. #define MAXN 79
  8.  
  9. struct cardstruct {                 /* global pattern */
  10.     char *first, *last, *middle;
  11.     long street_num;
  12.     char *street, *city, *state;
  13.     long zip;
  14.     int  area_code;
  15.     long phone;
  16. };
  17.  
  18. main()
  19. {
  20.     int  i;
  21.     char *Str_Input();
  22.     long Lint_Input();
  23.     struct cardstruct card1, card2;
  24.  
  25.     for (i = 0; i < 2; i++) /* do twice */
  26.         {
  27.         printf("\nCard %d:\n\n", i + 1);
  28.  
  29.         card1.first         = Str_Input("First Name");
  30.         card1.last          = Str_Input("Last Name");
  31.         card1.middle        = Str_Input("Middle Name");
  32.         card1.street_num    = Lint_Input("Street Number");
  33.         card1.street        = Str_Input("Street Name");
  34.         card1.city          = Str_Input("City");
  35.         card1.state         = Str_Input("State");
  36.         card1.zip           = Lint_Input("Zip Code");
  37.         card1.area_code     = (int)Lint_Input("Area Code");
  38.         card1.phone         = Lint_Input("Phone Number");
  39.  
  40.         if (i == 0)
  41.             card2 = card1;      /* structure assignment */
  42.         }
  43.     Showcard(card2);
  44.     Showcard(card1);
  45.  
  46. }
  47.  
  48. Showcard(struct cardstruct card)
  49. {
  50.     printf("\n\n");
  51.  
  52.     printf("%s %s %s\n", card.first, card.middle, 
  53.             card.last);
  54.     printf("%ld %s, %s, %s %ld\n", card.street_num, 
  55.             card.street, card.city, card.state,
  56.             card.zip);
  57.     printf("(%d) %ld\n", card.area_code, card.phone);
  58. }
  59.  
  60. char *Str_Input(char *prompt)
  61. {
  62.     char buf[MAXN + 1], *ptr;
  63.  
  64.     printf("%s: ", prompt);
  65.     if (fgets(buf, MAXN, stdin) == NULL)
  66.         exit(0);
  67.     buf[strlen(buf) - 1] = '\0'; /* strip '\n' */
  68.     if (strlen(buf) == 0)
  69.         exit(0);
  70.     if ((ptr = strdup(buf)) == NULL)
  71.         exit(0);
  72.     return (ptr);
  73. }
  74.  
  75. long Lint_Input(char *prompt)
  76. {
  77.     char buf[MAXN + 1];
  78.     long num;
  79.  
  80.     printf("%s: ", prompt);
  81.     if (fgets(buf, MAXN, stdin) == NULL)
  82.         exit(0);
  83.     if (sscanf(buf, "%ld", &num) != 1)
  84.         exit(0);
  85.     return (num);
  86. }
  87.