用程序运行search()函数查询学生信息时,文件中有学生信息,但是每次输入学号或姓名后都显示“查无此人”。这个该怎么办呢?
search()函数代码如下:
void search() //该函数用于查询学生信息
{
int searchmode; //子菜单选择
int i,j = 0,findid;
char findname[10];
int findok; //定义一个判断标志的整型变量findok
char findct; //定义一个用于判断是否继续查找的字符变量findct
FILE * fp; //定义一个文件指针fp
fp = fopen("students.txt", "r"); //以"只读"方式打开students文本文件
/*查询菜单*/
printf("\t\t成绩查询");
printf("\n\t1按姓名查询");
printf("\n\t2按学号查询");
printf("\n\t0返回上级菜单");
printf("\n请输入您的操作:");
scanf("%d", &searchmode);
/*查询操作*/
switch (searchmode)
{
case 1:
{
printf("请输入要查询学生的姓名:\n");
getchar();
scanf("%s", findname);
for (i = 0; i < n; i++)
{
fread( & st[i], sizeof(struct Student), 1, fp); //读入students文本文件
if (strcmp(st[i].name, findname) == 0) //比较字符串
{
j++;
printf("\n查寻到的学生为:\n");
printf("|#学号\t\t姓名\t性别\t年龄\t数学分析\t高等代数\t程序设计\t大学英语\tGPA\t#|\n");
printf(" %d ", st[i].id);
printf(" %-s ", st[i].name);
printf(" %-s ", st[i].gender);
printf(" %d ", st[i].age);
printf("\t%d ", st[i].MathAna);
printf("\t\t%d ", st[i].LiAlg);
printf("\t\t%d ", st[i].Computer);
printf("\t\t%d ", st[i].English);
printf("\t\t%.2f \n", st[i].GPA);
}
}
if (j == 0)
printf("\n>>>查无此人!");
//提示是否继续
printf("\n是否继续查找(Y/N)?");
getchar();
findct = getchar(); //从键盘输入一个判断字符,并将它赋值给字符变量findct,用于以下的if语句的判断
if (findct == 'Y' || findct == 'y')
search();
}
break;
case 2:
{
printf("请输入要查询学生的学号:");
scanf("%d", &findid);
for (i = 0; i < n; i++)
{
fread( & st[i], sizeof(struct Student), 1, fp); //以结构体students的方式从文件fp中读取,将其读入students文本文件,每次读入一个学生的信息
if (st[i].id == findid) //整型数字的比较
{
findok = 1;
break;
}
else findok = 0;
}
if (!findok)
printf("\n>>>查无此人!");
else
{
printf("\n查寻到的学生为:\n");
printf("|#学号\t\t姓名\t性别\t年龄\t数学分析\t高等代数\t程序设计\t大学英语\tGPA\t#|\n");
printf(" %d ", st[i].id);
printf(" %-s ", st[i].name);
printf(" %-s ", st[i].gender);
printf(" %d ", st[i].age);
printf("\t%d ", st[i].MathAna);
printf("\t\t%d ", st[i].LiAlg);
printf("\t\t%d ", st[i].Computer);
printf("\t\t%d ", st[i].English);
printf("\t\t%.2f \n", st[i].GPA);
}
//提示是否继续
printf("\n是否继续查找(Y/N)?");
getchar();
findct = getchar(); //从键盘输入一个判断字符,并将它赋值给字符变量findct,用于以下的if语句的判断
if (findct == 'Y' || findct == 'y')
search();
}
break;
}
fclose(fp); //关闭文件
}