
#include<stdlib.h>
#include <time.h>
#define STU_NUM_MAX 64 // 假设最多有64个学生
struct Student
{
char name[10]
int stuID
}stu[STU_NUM_MAX]
int exist[STU_NUM_MAX] // 用以保存被点过名
static int index=0 // 记住点名的次数
void Iitialize(){
for(int i=0i<STU_NUM_MAXi++) exist[i]=0
}
bool IsExist(int id){
for(int i=0i<STU_NUM_MAXi++)
if(exist[i]==id) return true //已存在
return false // 不存在
}
void Add() // 添加数据
{
FILE *fp
int stu_num
printf("\t\t You want to input the number of student?:")
scanf("%d",&stu_num)
for (int i=0i<stu_numi++){
printf("\n")
printf("\t\tPlease input student ID:")
scanf("%d",&stu[i].stuID)
printf("\t\tPlease input student name:")
scanf("%s",stu[i].name)
fflush(stdin)
}
if((fp=fopen("stu.dat","ab"))==NULL) {
printf("Can't open file\n")
exit(1)
}
for(int j=0j<stu_numj++)
{
if(fwrite(&stu[j],sizeof(struct Student),1,fp)!=1)
printf("Error writing file.\n")
}
fclose(fp)
}
void rollcall() // 随机点名
{
FILE *fp
if((fp=fopen("stu.dat","rb"))==NULL)
{
printf("Can't open file.\n")
exit(1)
}
srand((unsigned)time(NULL))
int i=0
int randID=rand()%(64-1+1)+1 // 1~64
printf("\t\t随机点到的学号为:%d\n\t\t%s\t%s\n",randID,"StuID","StuName")
do
{
fseek(fp,i*sizeof(struct Student),SEEK_SET)
if(fread(&stu[i],sizeof(struct Student),1,fp))
{
if(stu[i].stuID==randID&&!IsExist(randID)){
printf("\t\t%4d\t%5s\n",stu[i].stuID,stu[i].name)
exist[index++]=randID
break}
}
i++
}while(!feof(fp))
fclose(fp)
}
int main()
{
int select=0
char answer='y'
Iitialize()
do
{
printf("1.添加数据 2.随机点名 3.退出\n请选择:")
fflush(stdin)
scanf("%d",&select)
switch(select)
{
case 1:
Add()
break
case 2:
rollcall()
break
case 3:
return 0
}
fflush(stdin)
printf("You want to continue?:")
scanf("%c",&answer)
} while (answer=='y'||answer=='Y')
return 0
}
上面的代码,我留下几个细节问题留给你自己学着解决,都是很简单的:
上面的代码,我没有对重复的学号作判断。
上面的代码,我没有把点名存放到另一个文件,而是用数组替代(可以实现的也很简单)。我怕写得代码太多,百度限制提交。
上面的代码,是测试数据,stu.dat目标文件并没有64个学生,我只写入了12条数据。
上面的代码,我没有对数据数量(最多64条)作判断。
设置一个足够大的随机池,给每一个学生分配相同的空间,然后利用随机数来选取被点名的学生,同时对该学生所分配的空间和其他学生的空间进行缩减或增加。然后执行下一轮。大致思路就是这样,希望能够帮到你哦~
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)