C语言实例解析精粹学习笔记——32

实例32:

  编制一个包含姓名、地址、邮编和电话的通讯录输入和输出函数。

思路解析:

  1、用结构体来完成姓名、地址、邮编和电话的组合。

  2、结构体指针的使用。

  3、malloc的使用

  4、scanf函数的返回值是正确输入的变量个数

程序代码如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 #define ZIPLEN  10
 6 #define PHONLEN 15
 7 
 8 struct stu
 9 {
10     char *name;           //姓名
11     char *address;        //地址
12     char zip[ZIPLEN];     //邮政编码
13     char phone[PHONLEN];  //电话号码
14 };
15 
16 int readstu(struct stu *dpt);   /* 函数readstu用于输入一个通信录函数 */
17 int writestu(struct stu *dpt);  /* 函数writestu用于输出通讯录 */
18 
19 int main()
20 {
21     struct stu p[2];            /*示例用,只有两个元素的数组*/
22     int i,j;
23     for(i=0; i<2;i++)readstu(p+i);
24     for(j=0; j<i; j++)
25         writestu(p+j);
26     puts("\n Press any key to quit...");
27     return 0;
28 }
29 
30 int readstu(struct stu *dpt)
31 {
32     int  len;
33     char buf[120];
34 
35     printf("\nPlease input the Name:\n");
36     if(scanf("%s",buf) == 1)
37     {
38         len = strlen(buf);
39         dpt->name = (char *)malloc(len+1);
40         strcpy(dpt->name,buf);
41     }
42     else
43         return 0;
44     printf("Please input the Address:\n");
45     if(scanf("%s",buf) == 1)
46     {
47         len = strlen(buf);
48         dpt->address = (char *)malloc(len+1);
49         strcpy(dpt->address, buf);
50     }
51     else
52     {
53         free(dpt->name);
54         return 0;
55     }
56     printf("Please input the Zip code:\n");
57     if(scanf("%s",buf) == 1)
58         strncpy(dpt->zip,buf,ZIPLEN-1);
59     else
60     {
61         free(dpt->name);
62         free(dpt->address);
63         return 0;
64     }
65     printf("Please input the Phone number:\n");/*输入电话号码*/
66     if(scanf("%s",buf)==1)
67         strncpy(dpt->phone,buf,PHONLEN-1);
68     else
69     {
70         free(dpt->name);
71         free(dpt->address);
72         return 0;/*Ctrl+Z结束输入*/
73     }
74     return 1;
75 }
76 
77 int writestu(struct stu *dpt)
78 {
79     printf("Name    :   %s\n", dpt->name);
80     printf("Address :   %s\n", dpt->address);
81     printf("Zip     :   %s\n", dpt->zip);
82     printf("Phone   :   %s\n\n",dpt->phone);
83 }

 

posted @ 2018-10-05 17:03  llccbb1  阅读(127)  评论(0编辑  收藏  举报