机试题目中的文件操作

烈酒焚心 提交于 2019-11-27 00:24:15

参考网址

头文件

#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;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!