您的位置:首页 > 编程语言

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

2012-12-28 10:08 1631 查看
《转自论坛》

#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();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  学生 读取 写入 文件
相关文章推荐