C++将“文本文件”改为“二进制文件”,
为什么我编的程序不可以求大神给指导改正#include<iostream>#include<fstream>#include<string>usingnamespaces...
为什么我编的程序不可以 求大神给指导改正
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Student
{
public:
string no;
string name;
string sex;
string major;
string phone;
string addr;
};
int main()
{
Student stud;
ifstream infile("stu.txt",ios::binary);
if(!infile)
{
cerr<<"open error"<<endl;
abort();
}
infile.read((char*)&stud,sizeof(stud));
infile.close();
cout<<"学号:";
cout<<stud.no<<endl;
cout<<"姓名:";
cout<<stud.name<<endl;
cout<<"性别:";
cout<<stud.sex<<endl;
cout<<"专业:";
cout<<stud.major<<endl;
cout<<"电话:";
cout<<stud.phone<<endl;
cout<<"地址:";
cout<<stud.addr<<endl;
return 0;
} 展开
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Student
{
public:
string no;
string name;
string sex;
string major;
string phone;
string addr;
};
int main()
{
Student stud;
ifstream infile("stu.txt",ios::binary);
if(!infile)
{
cerr<<"open error"<<endl;
abort();
}
infile.read((char*)&stud,sizeof(stud));
infile.close();
cout<<"学号:";
cout<<stud.no<<endl;
cout<<"姓名:";
cout<<stud.name<<endl;
cout<<"性别:";
cout<<stud.sex<<endl;
cout<<"专业:";
cout<<stud.major<<endl;
cout<<"电话:";
cout<<stud.phone<<endl;
cout<<"地址:";
cout<<stud.addr<<endl;
return 0;
} 展开
1个回答
展开全部
你只是读文件,又没有写文件。怎么能把文本文件变成二进制文件?
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Student
{
public:
string no;
string name;
string sex;
string major;
string phone;
string addr;
};
int main()
{
Student stud;
stud.no="1046";
stud.name="zxy";
stud.sex="M";
stud.major="测试技术";
stud.phone="1111112334";
stud.addr="ji挺地址";
fstream infile("stu.txt",ios::in|ios::out|ios::binary);
if(!infile)
{
cerr<<"open error"<<endl;
abort();
}
infile.write((char*)&stud,sizeof(stud));
//写入二进制文件。
infile.close();
return 0;
}
追问
int main()
{
Student stud;
fstream infile("stu.txt",ios::in|ios::out|ios::binary);
infile.write((char*)&stud,sizeof(stud));
infile.close();
return 0;
}
显示的为空信息 转换也不对 是不是哪里还有错误呢..
追答
你的stud里面有没有数据?你这个只是初始化了。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询