南邮c++实验 文件中选课和选课人数问题 代码
#include<fstream>
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Course
{
string name;
int number;
public:
Course(string na = "", int num = 0);
friend ostream& operator<<(ostream& out, const Course& p);
friend istream& operator>>(istream& in, Course& p);
};
ostream& operator<<(ostream& out, const Course& p)
{
out << p.name << setw(10) << p.number << endl;
return out;
}
istream& operator >>(istream& in, Course& p)
{
in >> p.name >> p.number;
return in;
}
Course::Course(string na, int num)
{
name = na;
number = num;
}
int main()
{
ofstream out("d:\\course.txt");
if (!out)
{
cout << "course.txt cannot be openned";
return 0;
}
Course course[3] = { Course("高级语言程序设计",3018),
Course("面向对象程序设计及c++",487),
Course("程序设计(实践)",2046)
};
for (int j = 0; j <= 2; j++)
{
out << course[j];
}
out.close();
ifstream in("d:\\course.txt");
if (!in)
{
cout << "course.txt cannot be openned" << endl;
return 0;
}
int i = 0;
while (i < 3)
{
in >> course[i];
cout << course[i];
i++;
}
in.close();
return 0;
}