修改后的程序如下:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <stdio.h>
class student
{
private:
int sum;
int grade;
static int aver;
static int number;
static long place;
public:
student()
{
number++;
}
void insete_txt(int study,char *name,int grade)
{
fstream f("stu.txt",ios::out|ios::app);
f<<study<<endl;
f<<name<<endl;
f<<grade<<endl;
f.close();
}
void output_c(int sum)
{
char name[10];
int study,grade,i;
cout<<"∷∷∷∷∷∷∷∷∷∷★☆☆☆★【学生信息统计】★☆☆☆★∷∷∷∷∷∷∷∷∷∷∷"<<endl;
fstream f;
f.open("stu.txt",ios::in);
f.seekg(place,ios::beg);
//用seekg函数定位指针读取时的位置;其中place已经获得本次追加文件的开头;
for(i=0;i<sum;i++)
{
cout<<"---------第"<<i+1<<"位学生的信息:--------"<<endl;
f>>study;
f>>name;
f>>grade;
cout<<"学号:"<<study<<endl;
cout<<"姓名:"<<name<<endl;
cout<<"成绩:"<<grade<<endl;
}
f.close();
}
void average(int grade)
{
aver=aver+grade;
}
void summa()
{
aver=aver/number;
cout<<"------------------------------------------------------------------------------"<<endl;
cout<<"\n【本班学生平均分为:"<<aver<<"】"<<endl;
cout<<"\n\n\n\n\n∷∷∷∷∷∷∷∷∷∷∷『作者:韩震 日期:2006年4月15日』∷∷∷∷∷∷∷∷∷∷∷∷"<<endl;
getchar();
}
void play()
{
fstream f("stu.txt",ios::out|ios::app); //以追加的形式打开文件;为了得到当前文件指针位置
place=f.tellp(); //把当前位置赋给静态变量place;
f.close();
}
};
class display
{
public:
void show()
{
cout<<"∷∷∷∷∷∷∷∷∷∷★☆☆☆★【学生信息系统】★☆☆☆★∷∷∷∷∷∷∷∷∷∷∷"<<endl;
cout<<"\n\n";
cout<<"『OK!学生信息录入完成!』"<<endl;
cout<<"\n\n\n\n\n\n\n";
cout<<"「功能选项:」\t"<<"〖[Y]→显示学生信息〗\t"<<"〖[N]→退出程序〗"<<"\n\n\n\n\n";
}
void show2()
{
cout<<"∷∷∷∷∷∷∷∷★☆☆☆★【欢迎登陆学生信息系统】★☆☆☆★∷∷∷∷∷∷∷∷∷"<<endl;
cout<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl<<endl;
cout<<"『要清除数据库中原有数据请按: y ;否则的话按任意字符+Enter继续.......』";
}
void show3()
{
cout<<"∷∷∷∷∷∷∷∷∷∷★☆☆☆★【学生信息录入】★☆☆☆★∷∷∷∷∷∷∷∷∷∷∷"<<endl;
}
};
int student::number;
int student::aver=0;
long student::place=0;
void main()
{
int study,grade,sum,i;
char name[10],select,select1;
display dis;
dis.show2();
cin>>select1;
if(select1=='y'||select1=='Y')
{
fstream f("stu.txt",ios::trunc);
f.close();
system("cls");
}
else
{
system("cls");
}
dis.show3();
cout<<endl<<endl<<endl<<endl<<endl;
cout<<"\t〖请输入学生个数〗:";
cin>>sum;
system("cls");
student *stu;
stu=new student[sum];
(*stu).play(); //写入之前调用函数,获得当前指针的位置;
for(i=0;i<sum;i++)
{
dis.show3( );
cout<<"\t〖第"<<i+1<<"位学生信息〗"<<endl;
cout<<"输入学号:";
cin>>study;
cout<<"输入姓名:";
cin>>name;
cout<<"输入成绩:";
cin>>grade;
(*(stu+i)).insete_txt(study,name,grade);
(*(stu+i)).average(grade);
system("cls");
}
dis.show();
cout<<"\tselect:";
cin>>select;
if(select=='y'||select=='Y')
{
system("cls");
(*stu).output_c(sum);
(*stu).summa();
}
delete [] stu;
}
程序中我已经使用了指针来控制文件读取的位置但是它还是每次都从第一行开始读取,
实在搞不明白。应为是初学C++还请 师兄们帮帮忙啊.谢谢你们了~~!
接受tellp()的值的变量已经改为long型;但是他怎么还是从文件开头开始读取呀指针没有起到作用呀;
[此贴子已经被作者于2006-4-18 17:16:59编辑过]