24行中,b.time 和b.tickets前面都需要 &符号。
另外,b是结构体数组,fscanf函数中应该用 b[n].depart, b[n].arrived, &b[n].time, &b[n].tickets
(2)第30行,改成 total = count(b,n,a_name); 不需要写[]
(3)17行,if (fp=Fopen ("info.txt","r")=nuIl) 改成
if((fp=fopen("info.txt","r")) == NULL)
(4)count函数中,int i,C;这里,C没有初始化,改成 int i,C=0;
strcmp()函数判断字符串相等时,需要用if (strcmp(arr[i].arrived, M) == 0)才行。
代码修改如下
#include <stdio.h>
#include <string.h>
#define Max 100
struct bus {
char depart[6]; //出发时间
char arrived[10]; //终点
int time; //行车时间(分钟)
int tickets; //已定票人数
};
int count(struct bus arr[], int n, char M[]);
int main()
{
FILE* fp;
struct bus b[Max];
int n = 0, total = 0;
char a_name[10];
if ((fp = fopen("info.txt", "r")) == NULL)
{
printf("Cann't find File\n");
return 0;
}
while (!feof(fp))
{
if (fscanf(fp, "%s%s%d%d", b[n].depart, b[n].arrived, &b[n].time, &b[n].tickets)) //这里最好放在if语句中,避免读取失败导致n++多执行
n++;
}
fclose(fp);
printf("请输入终点站名称:");
gets(a_name);
total = count(b, n, a_name);
printf("到达%s的班次为:%d", a_name, total);
return 0;
}
int count(struct bus arr[], int n, char M[])
{
int i, C = 0;
for (i = 0; i < n; i++)
{
if (strcmp(arr[i].arrived, M) == 0) //修改
C = C + 1;
}
return C;
}
有几处小地方有错误,如从文件读取数据那里错了,文件判断为空那里需要用括号括起来,然后存储班车次数的变量要初始化为0。
修改如下:
#include <stdio.h>
#include <string.h>
#define Max 100
struct bus{
char depart[6];
char arrived[10];
int time;
int tickets;
};
int count(struct bus arr[],int n,char M[]);
int main(void){
FILE * fp;
struct bus b[Max];
int n=0, total=0;
char a_name[10];
// 这里fp赋值的这个表达式括起来
if((fp=fopen("info.txt","r"))==NULL){
printf("Cann't find File");
return 0;
}
while(!feof(fp)){
// 读取整数时,前面的变量加一个&,表示取其地址
fscanf(fp,"%s%s%d%d",b[n].depart,b[n].arrived,&b[n].time,&b[n].tickets);
// printf("%s %s %d %d\n",b[n].depart,b[n].arrived,b[n].time,b[n].tickets);
n++;
}
fclose(fp);
printf("请输入终点站名称:");
gets(a_name);
// 这里传入结构数组名
total = count(b,n,a_name);
printf("达到%s的班车次数为:%d",a_name,total);
return 0;
}
int count(struct bus arr[],int n,char M[]){
int i,c=0; // 班车次数初始化为0
for(i=0;i<n;i++){
if(strcmp(arr[i].arrived,M)==0){
c=c+1;
// printf("arr[%d].arrived=%s,M=%s,c=%d\n",i,arr[i].arrived,M,c);
}
}
return c;
}
info.txt(测试数据文件,和代码放置在同一个目录):
5-13 广州 10 20
5-13 北京 8 30
5-13 深圳 10 23
5-14 深圳 10 24
5-14 北京 9 35
5-14 深圳 11 19
5-14 广州 12 28