设计一个学生类,其中包含学号、姓名、成绩等数据成员,创建学生对象并且倒入到文件file.txt,然后由文件读取到另一个学生对象并输出,试编程实现。

来源:互联网 发布:工作流程图软件 编辑:程序博客网 时间:2024/05/23 13:03
《转自论坛》

#include <iostream>
#include <fstream>
#include <stdexcept>


#include <cassert>
#include <cstdlib>


using namespace std;


class Student {
string number;
string name;
int score;
public:
Student(const char *number0, const char *name0, int score0);
bool writeToFile(const char *path) const ;
const Student readFromFile(const char *path) const;
void display() const;
};


Student::Student(const char *number0, const char *name0, int score0): number(number0), name(name0), score(score0)
{
}


bool Student::writeToFile(const char *path) const
{
assert(path);


ofstream file(path);
if(!file)
return false;


file << "number:" << number << endl;
file << "name:" << name << endl;
file << "score:" << score<< endl;
file.close();


return true;
}


const Student Student::readFromFile(const char *path) const
{
assert(path);


string number;
string name;
int score;


ifstream file(path);
if(!path)
throw runtime_error("open file to read failed");


string s;
while(file >> s) {
int pos = s.find(":");
if(s.substr(0, pos).compare("number") == 0) 
number = s.substr(pos + 1);
if(s.substr(0, pos).compare("name") == 0) 
name = s.substr(pos + 1);
if(s.substr(0, pos).compare("score") == 0) 
score = atoi(s.substr(pos + 1).c_str());
}


return Student(number.c_str(), name.c_str(), score);
}


void Student::display() const 
{
cout << "number: " << number << endl;
cout << "name: " << name << endl;
cout << "score: " << score << endl;
}


int main()
{
const char *filePath = "./file.txt";


Student stu("037165", "张三", 50);
stu.writeToFile(filePath);


Student stuCopy = stu.readFromFile(filePath);
stuCopy.display();
}