zoukankan      html  css  js  c++  java
  • 文件写入-结构体排序

    /*
    3、编写一个程序,实现如下功能:
    (1)将5个学生的信息(包括学号、姓名、成绩三项信息)写入到file1中。
    (2)从file1中读出5个学生的信息,按成绩自高到低排序,排序后的结果写入到文件file2中。
    */
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define N 5
    
    typedef struct student
    {
        int num;
        char name[8];
        float socre;
    }Student;
    
    //写入成绩并且返回stu值
    void write(char *file,FILE *fp,Student *stu)
    {
        if((fp=fopen(file,"w"))==NULL)
        {
            printf("文件创建失败");
            return;
        }
        
        for(int i=0;i<N;i++)
        {
            fprintf(fp,"%d %s %.2f
    ",stu[i].num,stu[i].name,stu[i].socre);
        }
        fclose(fp);
    }
    
    //排序准备写入文件2的数据
    Student *sort(Student *stu2)
    {
        Student tmp;//结构体临时变量,不要定义为*tmp会报错!!!
    
        //冒泡排序
        for(int i=0;i<N-1;i++)
        {
            for(int j=0;j<N-i-1;j++)
            {
                if(stu2[j].socre<stu2[j+1].socre)
                {
                    tmp     =  stu2[j];
                    stu2[j]  = stu2[j+1];
                    stu2[j+1]= tmp ;
                }
            }
        }
    }
    
    int main()
    {
        FILE *fp;
        char *file1="D:\test1.txt",*file2="D:\test2.txt";
    
        //准备成绩
        Student stu[N];
        printf("请输入五位个学生的学号/姓名/成绩(格式为xxxxx xx xx):
    ");
        for(int i=0;i<N;i++)
        {
            scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].socre);
            getchar();
        }
    
        //写入text1
        write(file1,fp,stu);
    
        //排序成绩
        Student *stu2;
        stu2 = sort(stu);
    
        //写入text2
         write(file2,fp,stu);
    
        system("pause");
    }
  • 相关阅读:
    扩展中国剩余定理
    bzoj 3816&&uoj #41. [清华集训2014]矩阵变换
    THUSC2017
    bzoj 4521: [Cqoi2016]手机号码
    bzoj 4871: [Shoi2017]摧毁“树状图”
    bzoj 2300 : [HAOI2011]防线修建
    bzoj 3853 : GCD Array
    HEOI 2017 游记
    bzoj3926: [Zjoi2015]诸神眷顾的幻想乡 广义后缀自动机模板
    bzoj 4310 跳蚤
  • 原文地址:https://www.cnblogs.com/huxiaobai/p/10205152.html
Copyright © 2011-2022 走看看