| |
| |
#include "stdio.h"
#include "stdlib.h"
struct {
char name[15];
char age[4];
char sex[6]; /*这大小都了*/
char room[20];
char ID[10];
char phone_num[12];
} stu[50];
int n=0; /*更合习惯*/
void Wfile(void) /*放在Creat_record()之前供调用*/
{
FILE *fp;
if((fp=fopen("phonebook.txt","wt"))==NULL) /*容易阅读*/
printf("Can not open file!\n");
else
{
fwrite(stu,sizeof(stu[0]),n,fp);/*看你的意思是一次性写入所有数据*/
fclose(fp);
printf("Has been saved!\n");
}
}
void Creat_record(void)
{
char ch;
printf("-------------This is a new record!-------------\n");
printf("Please Enter Name:\n");
gets(stu[n].name);
printf("Please Enter Age:\n");
gets(stu[n].age);
printf("Please Enter Sex:\n");
gets(stu[n].sex);
printf("Please Enter Room:\n");
gets(stu[n].room);
printf("Please Enter ID:\n");
gets(stu[n].ID);
printf("Please Enter Phone_num:\n");
gets(stu[n].phone_num);
n++;
printf("Do you want to save ? Please press 'Y' or 'N'...\n");
ch=getchar();
getchar();
if(ch=='y'||ch=='Y')
Wfile();
if(ch=='n'||ch=='N')
return;
}
void List_record(void)
{
int i=0;
for(;i<n;i++) /* 因为读数据时的n++,是在最后*/
{
printf("=============Record %d==================\n",i+1);
printf("Name:%s\n",stu[i].name);
printf("Age:%s\n",stu[i].age);
printf("Sex:%s\n",stu[i].sex);
printf("room:%s\n",stu[i].room);
printf("ID:%s\n",stu[i].ID);
printf("Phone_num:%s\n",stu[i].phone_num);
}
}
void Search_record(void)
{
int k=0;
char name[15];
printf("Please Enter the person name:\n");
gets(name);
for(;k<n;k++)
if(strcmp(name,stu[k].name)==0)
{
printf("Name:%s\n",stu[k].name);
printf("Age:%s\n",stu[k].age);
printf("Sex:%s\n",stu[k].sex);
printf("room:%s\n",stu[k].room);
printf("ID:%s\n",stu[k].ID);
printf("Phone_num:%s\n",stu[k].phone_num);
}
printf("It's not exist!\n"); /*完备结果*/
}
/*那个读文件楼主也没用,删了*/
int main()
{
char ch=1; /*函数定义在前,没必要再声明*/
printf("=================Welcome to the phonebook!=================\n");
while(ch)
{
printf("Press E to creat a new record\n");
printf("Press L to list the all record\n");
printf("Press S to search the record\n");
ch=getchar(); getchar();
switch(ch)
{
case 'e':
case 'E': Creat_record();break;
case 'l':
case 'L': List_record();break;
case 's':
case 'S': Search_record();break;
default : break; /*必要的*/
}
printf("Do you want to continue ? Please press 'Y' or 'N'...\n");
ch= (getchar()-'Y'==0?1:0); getchar(); /*必要的*/
}
return 0;
}