首页 > 其他 > 详细

机试题目中的文件操作

时间:2019-08-11 21:27:29      阅读:114      评论:0      收藏:0      [点我收藏+]

参考网址

头文件

#include <fstream>

以写模式打开文件

ofstream out("sf1.txt");

以读方式打开文件

 ifstream in("sf1.txt");

题目实例

从键盘输入4个学生的数据(包括姓名、年龄和成绩),并存放在文件sf1上。从该文件读出这些数据,按成绩从高到底排序,并输出其中成绩次高者的所有数据。

#include<iostream>
#include<fstream>
#include<algorithm>
using namespace std;

struct Student
{
    char name[50];
    int age;
    int score;
}st[4];

bool cmp(Student a, Student b)
{
    return a.score < b.score;
}

int main()
{
    Student s;
    ofstream out("sf1.txt");
    cout << "请输入四名学生的姓名、年龄、成绩:" << endl;
    for (int i = 0; i < 4; i++)
    {
        cin >> s.name >> s.age >> s.score;
        out << s.name << "  " << s.age << "  " << s.score << endl;
    }
    ifstream in("sf1.txt");
    cout << "name  " << "  age  " << "score  " << endl;
    for (int i = 0; i < 4; i++)
    {
        in >> st[i].name >> st[i].age >> st[i].score;
        cout << st[i].name << "  " << st[i].age << "  " << st[i].score << endl;
    }
    sort(st, st + 4, cmp);
    cout << "name  " << "  age  " << "score  " << endl;
    for (int i = 0; i < 4; i++)
        cout << st[i].name << "  " << st[i].age << "  " << st[i].score << endl;
    return 0;
}

 

机试题目中的文件操作

原文:https://www.cnblogs.com/yun-an/p/11336486.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!