《C语言及程序设计》实践参考——区号查询

返回:贺老师课程教学链接

【项目3-区号查询】
在文件PostCode.txt中,提供了全国各省城市的长途区号和邮政编码。请以这个文件为数据来源设计程序,输入城市名,输出该城市的相关的信息。
[参考解答]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int readDate();
int Search(char*,int);
void Show(int);
struct Code
{
    char province[20];//省
    char abbreviation[4];//省的简称
    char city[24];//市
    int areacode;//区号
    int zipcode;//邮编
};
struct Code codes[5000];
int n;
int main()
{
    char s[22];
    int index = -1;
    n=readDate();
    printf("请输入要查询的城市:");
    scanf("%s", s);
    index =Search(s,n);   
    if (index>=0)
        Show(index);
    else
        printf("没有该城市,或者城市输入有误。\n");
    return 0;
}

int readDate()  //读取数据,返回人数
{
    FILE *infile=fopen("postcode.txt","r");     //以输入的方式打开文件
    if(!infile)                 //测试是否成功打开
    {
        printf("open error!\n");
        exit(1);
    }

    int i=0;
    fscanf(infile, "%s %s %s %d %d", codes[i].province, codes[i].abbreviation, codes[i].city, &codes[i].areacode, &codes[i].zipcode);
    while(!feof(infile))
    {
        ++i;
        fscanf(infile, "%s %s %s %d %d", codes[i].province, codes[i].abbreviation, codes[i].city, &codes[i].areacode, &codes[i].zipcode);
    }
    fclose(infile);
    return i;
}


int Search(char *s,int n)  //顺序查找,待改进
{
    int i;
    for (i=0; i<n; i++)
        if (strcmp(codes[i].city, s)==0)
            return i;
    return -1;

}

void Show(int i)
{
    printf("省份:%s\n", codes[i].province);
    printf("简称:%s\n", codes[i].abbreviation);
    printf("城市:%s\n",codes[i].city);
    printf("区号:0%d\n",codes[i].areacode);
    printf("邮政编码:%d\n",codes[i].zipcode);
}
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迂者-贺利坚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值