主题:c++代码差的出错误代码么?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int N = 2;
class Student
{
int no;
char name[10];
int degree;
public:
Student(){};
void setvalue(int n, char na[], int d)
{
no=n;
strcpy(name,na);
degree=d;
}
void disp()
{
cout << no <<'\t' <<name <<'\t'<<degree<<endl;
}
};
int main()
{
int i,n,d;
char na[10];
Student obj[N],s;
fstream iofile;
iofile.open("data.dat", ios::in | ios::out);
for(i=0; i<N; i++)
{
cout << "Input" << i+1 << "Student data:" << endl;
cout << "number,name,score:";
cin >> n >> na >> d;
obj[i].setvalue(n,na,d);
}
for(i=0; i<N; i++)
{
iofile.write((char*)&obj[i], sizeof(obj[i]));
}
iofile.seekp(0,ios::beg);
cout << "number\t name \t score" <<endl;
for(i=0; i<N; i++)
{
iofile.read((char*)&s, sizeof(s));
s.disp();
}
iofile.close();
return 0;
}
程序运行正常,等到输入数据后,输出成乱码了。为何?为何???
#include <fstream>
#include <string>
using namespace std;
const int N = 2;
class Student
{
int no;
char name[10];
int degree;
public:
Student(){};
void setvalue(int n, char na[], int d)
{
no=n;
strcpy(name,na);
degree=d;
}
void disp()
{
cout << no <<'\t' <<name <<'\t'<<degree<<endl;
}
};
int main()
{
int i,n,d;
char na[10];
Student obj[N],s;
fstream iofile;
iofile.open("data.dat", ios::in | ios::out);
for(i=0; i<N; i++)
{
cout << "Input" << i+1 << "Student data:" << endl;
cout << "number,name,score:";
cin >> n >> na >> d;
obj[i].setvalue(n,na,d);
}
for(i=0; i<N; i++)
{
iofile.write((char*)&obj[i], sizeof(obj[i]));
}
iofile.seekp(0,ios::beg);
cout << "number\t name \t score" <<endl;
for(i=0; i<N; i++)
{
iofile.read((char*)&s, sizeof(s));
s.disp();
}
iofile.close();
return 0;
}
程序运行正常,等到输入数据后,输出成乱码了。为何?为何???