建立上图的一个txt文件:
1004 TOM 100
1002 lily 95
1001 ann 93
1003 lucy 98
用一个c程序读入这个表一个结构体数组中:
结构体如下:
//学生数据结构体
typedef struct student
{
int id; //学号
char name[10]; //姓名
int score; //成绩
} Student;
以学号为关键字,查找学生成绩
运行示例:
代码如下:
/*********************************
* 顺序查找
* 从文件读取一组数据
* 存入到结构体中
* 对比key查找
* *******************************/
#include
#include
//学生数据结构体
typedef struct student
{
int id; //学号
char name[10]; //姓名
int score; //成绩
} Student;
//函数声明
int sq_search(Student r[] , int n , int key);//顺序查找
int main(int argc , char *argv[])
{
Student r[4];
FILE *fp;
//判断命令行是否正确输入
if (argc!=2)
{
printf("命令行输入错误!");
return 0;
}
//判断文件是否成功打开
if ((fp = fopen(argv[1] , "r")) == NULL)
{
printf("文件打开失败!");
return 0;
}
//从文件中读取数据信息
for (size_t i = 0; i < 4; i++)
{
fscanf(fp , "%d %s %d",&(r[i].id),&(r[i].name),&(r[i].score));
}
//顺序查找
int key,i;
while (1)
{
printf("请输入要查找的学生的学号:");
scanf("%d",&key);
i = sq_search(r,4,key);
if (i!=-1)
{
printf("学号:%d\n姓名:%s\n成绩:%d\n",r[i].id,r[i].name,r[i].score);
}else
{
printf("列表中没有该学生的信息!");
}
}
return 0;
}
//顺序查找
int sq_search(Student r[] , int count , int key)
{
for (size_t i = 0; i < count; i++)
{
if (r[i].id==key)
{
return i;
}
}
return -1;
}