将学生信息写入文本文件。一个学生的信息包括姓名和成绩,这些信息分别写入文件。要求:(1)学生的信息用一个Student类的对象表示,包含string firstName、char mi、string ...
时间: 2024-05-15 17:14:18 浏览: 39
下面是一个示例代码,可以将学生信息写入到文本文件中:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student {
public:
string firstName;
char mi;
string lastName;
double score;
};
int main() {
ofstream outFile("students.txt");
if (!outFile) {
cerr << "ERROR: Could not open file." << endl;
return 1;
}
Student s;
cout << "Enter student information (first name, MI, last name, score):" << endl;
while (cin >> s.firstName >> s.mi >> s.lastName >> s.score) {
outFile << s.firstName << " " << s.mi << " " << s.lastName << endl;
outFile << s.score << endl;
}
outFile.close();
return 0;
}
```
在上面的代码中,我们定义了一个 `Student` 类来表示学生信息。然后我们使用 `ofstream` 类来创建一个输出文件流,将学生信息写入到 `students.txt` 文件中。
我们使用 `cin` 对象从控制台读取学生信息,并将信息写入到文件中。每个学生信息被写入两行,第一行包含了学生的姓名,第二行包含了学生的成绩。
最后,我们关闭了输出文件流,并返回程序执行成功的状态码。