在线等...C++中将文件A1的内空复制到文件A2中的程序错在哪里

来源:百度知道 编辑:UC知道 时间:2024/05/31 09:25:05
在线等...
为什么中文件A1A2中会有乱码,而且不能输出成绩

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class student{
private:
int chinese,math;
char name[15];
public:
student(){};
student(char* na,int ch,int ma){
strcpy(name,na);
chinese=ch;
math=ma;
}
void display(){
cout<<name<<"\t"<<chinese<<"\t"<<math<<endl;
}
};
void main(){
ofstream out("c:\\A1A2\\A1.dat",ios::out);
student s1("张三",85,90);
student s2("李四",79,96);
out.write((char*)&s1,sizeof(s1));
out.write((char*)&s2,sizeof(s2));
out.close();
ifstream in("c:\\A1A2\\A1.dat",ios::in);
student p1,p2;
in.seekg(0,ios::beg);

in.read((char*)&p1,sizeof(p

上机调试了一下,发现楼主的问题就是打开文件不正确:
ofstream out("c:\\A1A2\\A1.dat",ios::out);
文件的路径是不对的。这样文件创建不成功,也就没办法写入数据。这样访问的数据都是无效的,因此会出现乱码。而没有文件的同时,调用in2.eof()返回的永远是0,因此就造成了死循环。eof函数表示当访问到文件末位的时候,返回的是一个非零值。
设置文件路径,应该这样"C:\A\B\C\xxx.dat",C:\A\B\C\是实际存在的目录,也就是说系统中已经存在了C:\A\B\C\这样的目录。如果不存在,直接设置路径"C:\A\B\C\xxx.dat",那么系统会把文件存储成这样:C:\ABCxxx.dat,造成文件目录的不一致性。

还有就是,打开输入输出流之后,最后要关闭一下,否则会造成资源的泄露。

另外,读写dat文件的时候,最好指明用ios::binary的方式。而默认的方式就不用写出来了。如果要写出来,可以用"|"连接。

修改了一下你的程序,如下:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class student
{
private:
int chinese,math;
char name[15];
public:
student(){};
student(char* na,int ch,int ma)
{
strcpy(name,na);
chinese=ch;
math=ma;
}
void display()