随机点名系统
实训老师讲的,又学到了
贴下代码
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 int x=15; 5 6 int main() 7 { 8 FILE *fp; 9 char name[50][20]; 10 int i,flag; 11 fp=fopen("D:\\fan.txt","r");//首先在D盘建一个fan.txt,里面要有字符串,以回车或空格为间隔 12 for(i=0; i<x; i++) 13 { 14 fscanf(fp,"%s",name[i]); 15 } 16 fclose(fp); 17 18 srand((unsigned)time(NULL)); 19 for(i=0; i<x; i++) 20 { 21 flag=rand()%x; 22 printf("点名:"); 23 printf("%s\n",name[flag]); 24 } 25 }
还有一个,差不多
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 int x=10; 5 6 int main() 7 { 8 FILE *fp; 9 char name[50][20]= {"zhao","qian","sun","li"}; 10 int i,flag; 11 fp=fopen("D:\\fan.txt","wt");//在D盘建立fan.txt; 12 13 srand((unsigned)time(NULL)); 14 for(i=0; i<4; i++) 15 { 16 fprintf(fp,"%s\n",name[i]); 17 } 18 fclose(fp); 19 20 fopen("D\\:fan.txt","r"); 21 for(i=0; i<x; i++) 22 { 23 flag=rand()%4; 24 fscanf(fp,"%s",name[flag]); 25 printf("点名:"); 26 printf("%s\n",name[flag]); 27 } 28 fclose(fp); 29 }
还有:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<time.h> 4 int x=15; 5 6 int main() 7 { 8 FILE *fp; 9 char name[50][20],n[10]={"徐"}; 10 int i,flag; 11 fp=fopen("D:\\fan.txt","a");//追加一个字符串。 12 //fprintf(fp,"%s\n",n); 13 //fputs("xu\n",fp); 14 fprintf(fp,"徐\n",n); 15 fclose(fp); 16 17 fp=fopen("D:\\fan.txt","r");//首先在D盘建一个fan.txt,里面要有字符串,以回车或空格为间隔 18 rewind(fp);//指针移到文件头部 19 for(i=0; i<x; i++) 20 { 21 //fscanf(fp,"%s",name[i]); 22 fgets(name[i],x,fp); 23 } 24 fclose(fp); 25 26 srand((unsigned)time(NULL)); 27 for(i=0; i<x; i++) 28 { 29 flag=rand()%x; 30 printf("点名:"); 31 printf("%s\n",name[flag]); 32 } 33 }