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

一个简单的有关问题,但是小弟我还是不懂`

2012-03-09 
一个简单的问题,但是我还是不懂``#include iostream#include fstreamusingnamespacestdclassStudent{

一个简单的问题,但是我还是不懂``
#include <iostream>
#include <fstream>
using   namespace   std;
class   Student
{
public:
int   id;
char   name[20];
int   math;
void   write();
void   read();
};
void   Student::write()
{
Student   *std=new   Student;
int   flag=1;
ofstream   ofile;
ofile.open( "result.txt ");
if(ofile.fail())
{
cout < < "打开文件出错   " < <endl;
return;
}
while(flag)
{
cout < < "姓名:   ";
cin> > std-> name;
        cout < < "学号:   ";
cin> > std-> id;
cout < < "数学:   ";
cin> > std-> math;
ofile < <std-> name < < "\t " < <std-> id < < "\t " < <std-> math < <endl;
cout < < "按0结束,其它继续 " < <endl;
cin> > flag;
}
ofile.close();
system( "PAUSE ");
}

void   Student::read()
{
Student   *std=new   Student;
ifstream   ifile;
ifile.open( "result.txt ");
if(ifile.fail())
{
cout < < "打开文件出错   " < <endl;
return;
}
        while(ifile.eof())
{
        ifile> > std-> name> > std-> id> > std-> math;

cout < < "姓名:   " < <std-> name < <endl;
cout < < "学号:   " < <std-> id < <endl;
cout < < "数学:   " < <std-> math < <endl < <endl;
}
ifile.close();
}

void   main()
{
      Student   *st=new   Student;
      st-> read();
      st-> write();
}

保存的时候没有什么问题,关键是读取的时候怎么读呢

或者说用什么方式比较好进行读取文件中的类信息呢

[解决办法]
//针对你的程序而言,很多地方不合理,很可能内存泄露就不说了
//仅仅满足能实现功能,这样改一下就可以读出来了
#include <iostream>
#include <fstream>
using namespace std;
class Student
{
public:
int id;
char name[20];
int math;
void write();
void read();
};
void Student::write()
{
Student *std=new Student;
int flag=1;
ofstream ofile;
ofile.open( "result.txt ");
if(ofile.fail())
{
cout < < "打开文件出错 " < <endl;
return;
}
while(flag)
{
cout < < "姓名: ";
cin> > std-> name;
cout < < "学号: ";
cin> > std-> id;
cout < < "数学: ";
cin> > std-> math;
ofile < <std-> name < < "\t " < <std-> id < < "\t " < <std-> math < <endl;
cout < < "按0结束,其它继续 " < <endl;
cin> > flag;
}
ofile.close();
system( "PAUSE ");
}

void Student::read()
{
Student *std=new Student;
ifstream ifile;
ifile.open( "result.txt ");
if(ifile.fail())
{
cout < < "打开文件出错 " < <endl;
return;
}
//while(ifile.eof())
//{
ifile> > std-> name> > std-> id> > std-> math;

cout < < "姓名: " < <std-> name < <endl;


cout < < "学号: " < <std-> id < <endl;
cout < < "数学: " < <std-> math < <endl < <endl;
//}
ifile.close();
}

void main()
{
Student *st=new Student;
st-> read();
st-> write();
}

热点排行