首页 新闻 会员 周边

C++文件的读取

0
悬赏园豆:5 [已解决问题] 解决于 2012-11-02 22:13
 1 #include <fstream>
 2 #include <iostream>
 3 #include <iomanip>
 4 #include <string>
 5 using namespace std;
 6 
 7 class Student
 8 {
 9 public:
10     
11     Student()
12     {
13         num = "";
14         name = "";
15     }
16 
17     Student(string n,string nam)
18     {
19         num = n;
20         name = nam;
21     }
22 
23     void show_basic_information()
24     {
25         cout << setw(10) << num << setw(8) << name << endl;
26     }
27 
28     string num;             //学号
29     string name;            //姓名
30 };
31 
32 //**********************写进文件***************************
33 void write()   
34 {
35     Student stu[2] = {Student("2011011","何十一") , Student("2011012","薛十二")};
36     ofstream outfile("D.txt" , ios::out|ios::binary);  
37     if(!outfile)
38     {
39         cout << "D.txt error!" << endl;
40         exit(1);
41     }
42     outfile.write( (char*)&stu[0] , sizeof(stu));
43     outfile.close();
44 }
45  
46 //**********************读取文件***************************
47 void read()
48 {
49     Student stud[2];
50     ifstream infile("D.txt",ios::in|ios::binary); 
51     if(!infile)
52     {
53         cout << "D.txt error!" << endl;
54         exit(1);
55     }
56     infile.read( (char*)&stud[0] , sizeof(stud) ); 
57     for(int i = 0; i < 2 ; i++)
58     {
59         stud[i].show_basic_information();
60     }
61     infile.close();
62 }
63 
64 int main()
65 {
66     write();
67     read();
68     return 0;
69 }

各位牛人 这程序哪错了啊 我用的是VC6.0 

wusi的主页 wusi | 初学一级 | 园豆:189
提问于:2012-10-31 13:09
< >
分享
最佳答案
0
在read()函数里,Student stud[2];实际是存储的是指向Student对象的两个指针。存储student的内存还没有分配,所以在写入时程序会崩溃。
你需要使用new 开辟足够空间。
但是有一个问题是,Student类里用了String,你使用二进制存储对象时,不会存储String的内容。
建议你还是重载<<与>>运算符,规定好序列化方法。也可以使用现有的库:xml库或json库都可以,自己选择吧。
收获园豆:5
许通 | 菜鸟二级 |园豆:220 | 2012-11-02 21:56

谢谢谢谢啊

wusi | 园豆:189 (初学一级) | 2012-11-02 22:12
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册