首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++ fstream如何读取链表

2013-05-02 
C++fstream怎么读取链表?本人新手,完全菜鸟,望大神们指教 o(∩_∩)o 学生管理系统,想要实现可以保存数据到硬

C++ fstream怎么读取链表?
     本人新手,完全菜鸟,望大神们指教 o(∩_∩)o 

学生管理系统,想要实现可以保存数据到硬盘


C++  fstream如何读取链表



C++  fstream如何读取链表


在程序开始的时候读数据。。。。


C++  fstream如何读取链表


结尾的时候保存数据。。。。


第一次执行的时候,可以执行

第二次开启,就出现
C++  fstream如何读取链表



菜鸟不太懂C++,求指教     感激不尽 C++ 链表
[解决办法]
1,结构体中不要使用string等不确定长度的字段
2,不要使用ifstream去读取,因为ifstream会把最后一个 结构体 多读一次。
[解决办法]
1. Student类的next需要在构造函数置0,否则运行时候指不定等于什么,会引起崩溃
2. 把对象保存到文件,或者通过网络传输这种问题是序列化问题(serialization),有很多通用的序列化库,比如boost::serialization,可以google c++ 序列化。
如果只是简单的保存,参考这个

#include <iostream>
#include <string>
#include <fstream>

using namespace std;


#pragma once


// save基本类型 int,double, float,bool...
template <class Stream, class T>
void serialize(Stream& stream, T& x) {
stream.write((const char*)&x, sizeof(T));
}
// load
template <class Stream, class T>
void de_serialize(Stream& stream, T& x) {
stream.read((char*)&x, sizeof(T));
}

// 指针
template <class Stream, class T>
void serialize(Stream& stream, T* x) {
bool is_not_null_ptr = x != 0;
serialize(stream, is_not_null_ptr);
if(x) {// if x != 0
serialize(stream, *x);
}
}
template <class Stream, class T>
void de_serialize(Stream& stream, T*& x) {
bool is_not_null_ptr;
de_serialize(stream, is_not_null_ptr);
if(is_not_null_ptr) {
x = new T;
de_serialize(stream, *x);
}
}

// std::string
template <class Stream>
void serialize(Stream& stream, const std::string& str) {
int len = str.length();
serialize(stream, len);
stream.write(str.c_str(), len);
}
template <class Stream>
void serialize(Stream& stream, std::string& str) {
serialize(stream, (const std::string&)str);
}

// string read
template <class Stream>
void de_serialize(Stream& stream, std::string& str) {
int len;
de_serialize(stream, len);
str.resize(len);
char x;
for(int i=0; i<len; i++) {
de_serialize(stream, x);
str[i] = x;
}
}


// 以上部分就是个简单的序列化库了


struct Student {
string num;
string name;
double score;
Student* next;

Student() : next(0) {} // next置0
Student(const string& num, const string& name, double score)
: num(num), name(name), score(score), next(0)
{}

void debug() {


cout << "name: " << name << ", num: " << num 
<< ", score: " << score << endl;
if(next) {
next->debug();
}
}
};

template<typename Stream>
void serialize(Stream& s, Student& stu) {
serialize(s, stu.num); //保存Student的各属性
serialize(s, stu.name);
serialize(s, stu.score);
serialize(s, stu.next);
}
template<typename Stream>
void de_serialize(Stream& s, Student& stu) {
de_serialize(s, stu.num);
de_serialize(s, stu.name);
de_serialize(s, stu.score);
de_serialize(s, stu.next);
}

int main() {
Student s1("111", "s1", 100);
Student s2("222", "s2", 60);
s2.next = &s1; // s2包含s1

ofstream ofs("save.txt", ios::binary);
serialize(ofs, s2);
ofs.close();

Student s3;
ifstream ifs("save.txt", ios::binary);
de_serialize(ifs, s3);

s3.debug();//就是上面s2的内容

}

热点排行