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

书上的例题居然显示乱码,泣血!

2012-04-23 
书上的例题居然显示乱码,泣血求助!!!最近在学c++,用的是谭浩强老师的《c++面向对象程序设计》,书上255页有个

书上的例题居然显示乱码,泣血求助!!!
最近在学c++,用的是谭浩强老师的《c++面向对象程序设计》,书上255页有个例题,随机访问二进制数据文件,因为我要做一个管理系统,所以要用到这个东西,我还把例题改简单了,结果运行后显示出来就变成这样了:
http://img.my.csdn.net/uploads/201204/17/1334649078_5003.png
弄了2天了,要疯了,泣血求助,是书上的例题有问题吗,还是我哪里错了,下面是源代码:
#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
struct student
{
int num;
char name[20];
float score;
};
int main()
{
student stud[2]={1001,"Li",85,1002,"Fun",90};//学生数据
fstream iofile("stud.dat",ios::in|ios::out|ios::binary|ios::trunc);//用输入输出二进制方式打开
if(!iofile)
{
cerr<<"open error!"<<endl;
abort();
}

for(int i=0;i<2;i++) //把学生数据录入数据文件"stud.dat"中
{
iofile.write((char*)&stud[i],sizeof(stud[i]));
}






student stud_new[2]; //用来放入数据文件中的学生数据

for(i=0;i<2;i++)
{
iofile.read((char*)&stud_new[i],sizeof(stud_new[i]));
cout<<stud_new[i].num<<stud_new[i].name<<stud_new[i].score<<endl;//显示从文件中得到的学生数据
}
iofile.close();
getch();
return 0;
}

[解决办法]
read时,指向的是文件尾吧。read失败。
[解决办法]
seekg下看看
[解决办法]
改成下面那样试试?

C/C++ code
include<conio.h>using namespace std;struct student{int num;char name[20];float score;};int main(){student stud[2]={1001,"Li",85,1002,"Fun",90};//学生数据fstream iofile("stud.dat",ios::in|ios::out|ios::binary|ios::trunc);//用输入输出二进制方式打开if(!iofile){cerr<<"open error!"<<endl;abort();}for(int i=0;i<2;i++) //把学生数据录入数据文件"stud.dat"中{iofile.write((char*)&stud[i],sizeof(stud[i]));}//ADD iofile.seekg(0,ios_base::beg);student stud_new[2]; //用来放入数据文件中的学生数据for(i=0;i<2;i++){iofile.read((char*)&stud_new[i],sizeof(stud_new[i]));cout<<stud_new[i].num<<stud_new[i].name<<stud_new[i].score<<endl;//显示从文件中得到的学生数据}iofile.close();getch();return 0;}
[解决办法]
iofile.seekp(0, ios::beg); //把文件指针放在开始位置,加这一句就OK

student stud_new[2]; //用来放入数据文件中的学生数据
[解决办法]
char name[20];
这个的数组声名都改成char name[20]={0};试试
[解决办法]
for(int i =0 ;i< 2 ;i++)
{
iofile.seekg(i*sizeof(student),ios::beg); //加入这部分代码
iofile.read((char*)&stu_new[i],sizeof(stu_new[i]));
cout<<stu_new[i].id<<endl;
cout<<stu_new[i].name<<endl;
cout<<stu_new[i].score<<endl;
}

热点排行