c语言 随机点名

要求如下1、生成随机数n(1〜64)
2、有一文件A 格式为:
01 张三三
02 李四四四(即有四字名称)
••••••
64 王一(即有2字名称)
抽取到的随机数n为学号 显示出对应学生名,同时将结果保存到文件b中
3、出现过的人名不再出现
我测试后运行良好会再加50分〜60分

#include<stdio.h>
#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=0;i<STU_NUM_MAX;i++) exist[i]=0;
}
bool IsExist(int id){
for(int i=0;i<STU_NUM_MAX;i++)
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=0;i<stu_num;i++){
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=0;j<stu_num;j++)
{   
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条)作判断。

追问

我想问一下 对重复的学号做判断要怎么做 用if检测吗
这个程序能否做到 在关闭一次后重新打开依然不重复
谢谢

追答

由于代码较长百度限制了提交,我下面截图给你看:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-12-12
好简单的程序,解决的方法很清晰,不过没时间做追问

帮个忙吧,这不用半小时的

相似回答