我的目的是用过这段程序分别向一个txt文本写入信息和向另一个txt文本以二进制形式写入信息,但是运行过后两个txt内容一样,有些信息是正确的有些是乱码,应该二进制录入信息的文本中内容和第一个文本一样,代码如下:
#include <iostream>
#include <fstream>
using namespace std;
class Student
{
private:
char no[10], name[20], sex[10];
char major[20], phone[20], addr[30];
public:
friend istream & operator>>(istream &, Student &);
friend ostream & operator<<(ostream &, Student &);
void writeTo(char filename[]);
void readFrom(char filename[]);
void writeTobinary(char filename[]);
void readFrombinary(char filename[]);
};
istream & operator>>(istream & input, Student & s)
{
cout << "输入学生数据:" << endl;
cout << "学号:";
input >> s.no;
cout << "姓名:";
input >> s.name;
cout << "性别:";
input >> s.sex;
cout << "专业:";
input >> s.major;
cout << "电话:";
input >> s.phone;
cout << "地址:";
input >> s.addr;
return input;
}
ostream & operator<<(ostream & output, Student & s)
{
output << "输出学生数据:" << endl;
output << "学号:" << s.no << endl;
output << "姓名:" << s.name << endl;
output << "性别:" << s.sex << endl;
output << "专业:" << s.major << endl;
output << "电话:" << s.phone << endl;
output << "地址:" << s.addr << endl;
return output;
}
void Student::writeTobinary (char filename[])
{
ofstream outFile;
outFile.open(filename,ios::binary|ios::out);
if(!outFile) cerr<<"open error!"<<endl;
else outFile.write((char *)this, sizeof *this);
outFile.close();
}
void Student::readFrombinary (char filename[])
{
ifstream inFile;
inFile.open(filename,ios::binary|ios::in);
if(!inFile) cerr<<"open error!"<<endl;
inFile>>no>>name>>sex>>major>>phone>>addr;
inFile.close();
}
void Student::writeTo (char filename[])
{
ofstream outFile;
outFile.open(filename,ios::out);
if(!outFile) cerr<<"open error!"<<endl;
else outFile.write((char *)this, sizeof *this);
outFile.close();
}
void Student::readFrom (char filename[])
{
ifstream inFile;
inFile.open(filename,ios::in);
if(!inFile) cerr<<"open error!"<<endl;
inFile>>no>>name>>sex>>major>>phone>>addr;
inFile.close();
}
int main(int argc, char* argv[])
{
Student stu1,stu2;
cin >> stu1;
stu1.writeTo("D:\\stu1.txt");
stu1.readFrom("D:\\stu1.txt");
cout << stu1;
cin >> stu2;
stu2.writeTobinary("D:\\stu2.txt");
stu2.readFrombinary("D:\\stu2.txt");
cout << stu2;
return 0;
}
如何解决?