问题及问题要求:
实例代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct{
char Pro[28];
char Abb[4];
char city[24];
int areacode;
int postalcode;
}city;
int cityNum; //用于记录城市数目
city cityCode[5000];
int readDate(); //读入数据,返回城市数量
int Search(char *,int); //查询
void show(int); //输出查询结果
int main(){
char s[28];
int index = -1;
cityNum = readDate();
printf("input need to query the name of the city:");
scanf("%s",s);
index = Search(s,cityNum);
if(index >= 0){
show(index);
}else{
printf("No city or city name is incorrectly entered!");
}
return 0;
}
int readDate()
{
int i = 0;
FILE *fp;
fp = fopen("PostCode.txt","r");
if(fp == NULL)
{
printf("open file error!");
exit(1); //需要stdlib.h
}
fscanf(fp,"%s %s %s %d %d",cityCode[i].Pro,cityCode[i].Abb,cityCode[i].city,&cityCode[i].areacode,&cityCode[i].postalcode);
while(!feof(fp))
{
++i;
fscanf(fp,"%s %s %s %d %d",cityCode[i].Pro,cityCode[i].Abb,cityCode[i].city,&cityCode[i].areacode,&cityCode[i].postalcode);
}
fclose(fp);
return i;
}
int Search(char *c,int n)
{
int i;
for(i = 0 ; i < n ; i++){
if(strcmp(c,cityCode[i].city) == 0){
return i;
}
}
return -1;
}
void show(int i)
{
printf("省份:%s\n",cityCode[i].Pro);
printf("简称:%s\n",cityCode[i].Abb);
printf("城市:%s\n",cityCode[i].city);
printf("区号:%d\n",cityCode[i].areacode);
printf("邮政编码:%d\n",cityCode[i].postalcode);
return;
}
运行演示:
成功查找:
失败查找: