头文件
#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