实例 32:
编制一个包含姓名, 地址, 邮编和电话的通讯录输入和输出函数.
思路解析:
1, 用结构体来完成姓名, 地址, 邮编和电话的组合.
2, 结构体指针的使用.
3,malloc 的使用
4,scanf 函数的返回值是正确输入的变量个数
程序代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define ZIPLEN 10
- #define PHONLEN 15
- struct stu
- {
- char *name; // 姓名
- char *address; // 地址
- char zip[ZIPLEN]; // 邮政编码
- char phone[PHONLEN]; // 电话号码
- };
- int readstu(struct stu *dpt); /* 函数 readstu 用于输入一个通信录函数 */
- int writestu(struct stu *dpt); /* 函数 writestu 用于输出通讯录 */
- int main()
- {
- struct stu p[2]; /* 示例用, 只有两个元素的数组 */
- int i,j;
- for(i=0; i<2;i++)readstu(p+i);
- for(j=0; j<i; j++)
- writestu(p+j);
- puts("\n Press any key to quit...");
- return 0;
- }
- int readstu(struct stu *dpt)
- {
- int len;
- char buf[120];
- printf("\nPlease input the Name:\n");
- if(scanf("%s",buf) == 1)
- {
- len = strlen(buf);
- dpt->name = (char *)malloc(len+1);
- strcpy(dpt->name,buf);
- }
- else
- return 0;
- printf("Please input the Address:\n");
- if(scanf("%s",buf) == 1)
- {
- len = strlen(buf);
- dpt->address = (char *)malloc(len+1);
- strcpy(dpt->address, buf);
- }
- else
- {
- free(dpt->name);
- return 0;
- }
- printf("Please input the Zip code:\n");
- if(scanf("%s",buf) == 1)
- strncpy(dpt->zip,buf,ZIPLEN-1);
- else
- {
- free(dpt->name);
- free(dpt->address);
- return 0;
- }
- printf("Please input the Phone number:\n");/* 输入电话号码 */
- if(scanf("%s",buf)==1)
- strncpy(dpt->phone,buf,PHONLEN-1);
- else
- {
- free(dpt->name);
- free(dpt->address);
- return 0;/*Ctrl+Z 结束输入 */
- }
- return 1;
- }
- int writestu(struct stu *dpt)
- {
- printf("Name : %s\n", dpt->name);
- printf("Address : %s\n", dpt->address);
- printf("Zip : %s\n", dpt->zip);
- printf("Phone : %s\n\n",dpt->phone);
- }
来源: http://www.bubuko.com/infodetail-2795646.html