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

初学者求教,实在不知道错哪了,编译没错,运行后有异常!

2012-05-07 
菜鸟求教,实在不知道哪里错了,编译没错,运行后有错误!!!请教,编译通过了,以下程序运行后会有错误:C++ proj

菜鸟求教,实在不知道哪里错了,编译没错,运行后有错误!!!
请教,编译通过了,以下程序运行后会有错误:
C++ project.exe 中的 0x5986ad4a (msvcp100d.dll) 处有未经处理的异常: 0xC0000005: 读取位置 0x001038f4 时发生访问冲突

位置在output_employee函数结束时有错误,但具体原因不知。。。 我是新手,望各位指点迷津,谢谢大家!

//source program:

#include<fstream>
#include<iostream>
#include<string>
using namespace std;

class Employee
{
public:
Employee(){num=0;name="x";age=1;salary=0.0;}
Employee(int n,string na,int a,int s):num(n),name(na),age(a),salary(s){}
friend ostream &operator<<(ostream &,Employee &);
void getvalue()
{
cout<<"Please input the data."<<endl;
cin>>num>>name>>age>>salary;
}
friend void sort(Employee*,int);
private:
int num;
string name;
int age;
int salary;
};

void filewrite(char *fname,Employee *pE)
{
ofstream outfile(fname,ios::binary);
if(!outfile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(int i=0;i<5;i++)
outfile.write((char*)&pE[i],sizeof(pE[i]));
outfile.close();
}

void sort(Employee *pE,int count)
{
Employee eTemp;
int ePos;
for(int i=0;i<count;i++)
{
eTemp=pE[i];
ePos=i;
for(int j=i+1;j<count;j++)
{
if(pE[j].num<eTemp.num)
{
eTemp=pE[j];
ePos=j;
}
}
pE[ePos]=pE[i];
pE[i]=eTemp;
}
}

ostream& operator<<(ostream& output,Employee& e2)
{
output<<"num:"<<e2.num<<" name:"<<e2.name<<" age:"<<e2.age<<" salary:"<<e2.salary<<endl;
return output;
}

void output_employee(char* fname)
{
Employee aemp[5];
ifstream infile(fname,ios::binary);
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(int i=0;i<5;i++)
infile.read((char*)&aemp[i],sizeof(aemp[i]));
infile.close();
cout<<"Here is the data:"<<endl;
for(int i=0;i<5;i++)
{
cout<<aemp[i];
}
}

int main()
{
Employee emp[5]={
Employee(2,"B",12,22),
Employee(5,"E",15,55),
Employee(1,"A",11,11),
Employee(4,"D",14,14),
Employee(3,"C",13,13)
};

sort(emp,5);
filewrite("employee.dat",emp);

output_employee("employee.dat");

return 0;
}

[解决办法]
参考:http://topic.csdn.net/u/20100730/12/71cf86d7-04ca-446c-b931-6c83d47d4c19.html

楼主要学会根据报的错查找资料哈~

string转换成为char*出现的错误

C/C++ code
class Employee{public:    Employee(){num=0;name='\0';age=1;salary=0;}    Employee(int n,char* na,int a,int s):num(n),age(a),salary(s)    {        int len = sizeof(na) +1;        name = new char [len];        name = na;    }    friend ostream &operator<<(ostream &,Employee &);    void getvalue()    {        cout<<"Please input the data."<<endl;        cin>>num>>name>>age>>salary;    }    friend void sort(Employee*,int);private:    int num;//    string name;    char* name;    int age;    int salary;};
[解决办法]
LZ,在CODEBLOCKS环境下验证没问题

热点排行