C++用类和文件实现学生记录处理程序
时间: 2023-06-20 19:06:16 浏览: 58
好的,以下是一个可能的实现:
### 学生类
```cpp
// student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
class Student {
public:
Student();
Student(const std::string& name, int id, double gpa);
~Student();
// getters
std::string getName() const;
int getId() const;
double getGpa() const;
// setters
void setName(const std::string& name);
void setId(int id);
void setGpa(double gpa);
// file I/O
void writeToFile(std::ofstream& file) const;
void readFromFile(std::ifstream& file);
private:
std::string m_name;
int m_id;
double m_gpa;
};
#endif // STUDENT_H
```
```cpp
// student.cpp
#include "student.h"
#include <iostream>
Student::Student() : m_name(""), m_id(0), m_gpa(0.0) {}
Student::Student(const std::string& name, int id, double gpa) :
m_name(name), m_id(id), m_gpa(gpa) {}
Student::~Student() {}
std::string Student::getName() const {
return m_name;
}
int Student::getId() const {
return m_id;
}
double Student::getGpa() const {
return m_gpa;
}
void Student::setName(const std::string& name) {
m_name = name;
}
void Student::setId(int id) {
m_id = id;
}
void Student::setGpa(double gpa) {
m_gpa = gpa;
}
void Student::writeToFile(std::ofstream& file) const {
file << m_name << " " << m_id << " " << m_gpa << std::endl;
}
void Student::readFromFile(std::ifstream& file) {
file >> m_name >> m_id >> m_gpa;
}
```
### 主程序
```cpp
#include <iostream>
#include <fstream>
#include "student.h"
const std::string FILENAME = "students.txt";
void addStudent(std::ofstream& file) {
std::string name;
int id;
double gpa;
std::cout << "Enter name: ";
std::getline(std::cin, name);
std::cout << "Enter ID: ";
std::cin >> id;
std::cout << "Enter GPA: ";
std::cin >> gpa;
Student student(name, id, gpa);
student.writeToFile(file);
std::cout << "Student added." << std::endl;
}
void printRecords(std::ifstream& file) {
Student student;
while (!file.eof()) {
student.readFromFile(file);
std::cout << "Name: " << student.getName() << std::endl;
std::cout << "ID: " << student.getId() << std::endl;
std::cout << "GPA: " << student.getGpa() << std::endl;
std::cout << std::endl;
}
}
int main() {
std::ofstream outfile(FILENAME, std::ios::app);
if (!outfile) {
std::cerr << "Failed to open file for writing." << std::endl;
return 1;
}
std::ifstream infile(FILENAME);
if (!infile) {
std::cerr << "Failed to open file for reading." << std::endl;
return 1;
}
int choice;
do {
std::cout << "1. Add student" << std::endl;
std::cout << "2. Print records" << std::endl;
std::cout << "0. Exit" << std::endl;
std::cout << "Enter choice: ";
std::cin >> choice;
switch (choice) {
case 1:
addStudent(outfile);
break;
case 2:
printRecords(infile);
break;
case 0:
std::cout << "Goodbye!" << std::endl;
break;
default:
std::cout << "Invalid choice." << std::endl;
break;
}
} while (choice != 0);
outfile.close();
infile.close();
return 0;
}
```
这个程序可以让用户添加学生记录到文件中,并在需要时从文件中打印学生记录。在这个实现中,文件是永久性存储的,学生记录在程序启动时从文件中读入,并在程序退出时写入文件。