界面顯示可以,但是打開檔案出現一些燙,如下:
張三 燙燙燙燙燙燙燙燙燙? 李四 燙燙燙燙燙燙燙燙燙? 〡 ( 王五 燙燙燙燙燙燙燙燙燙? X 劉六 燙燙燙燙燙燙燙燙燙? €慇
實在不懂,因為要做作業,憋了好幾天了
#include <iostream>
#include <fstream>
using namespace std;
class Employee{
private:
int number ,age;
char name[20];
double sal;
public:
Employee(){}
Employee(int num,char* Name,int Age, double Salary){
number=num;
strcpy(this->name,Name);
age=Age;
sal=Salary;
}
char * getName(){
return name;
}
void setName(char * name){
strcpy(this->name,name);
}
void addSalary(int sa){
this->sal+=sa;
}
void display(){
cout<<number<<"\t"
<<name<<"\t"
<<age<<"\t"<<sal<<endl;
}
};
int main()
{
ofstream out;
out.open("Employee.txt",ios::out|ios::binary);
Employee e1(1,"張三",23,2320);
Employee e2(2,"李四",32,3210);
Employee e3(3,"王五",34,2220);
Employee e4(4,"劉六",27,1120);
out.write((char*)&e1,sizeof(e1));
out.write((char*)&e2,sizeof(e2));
out.write((char*)&e3,sizeof(e3));
out.write((char*)&e4,sizeof(e4));
Employee e5(3,"王五",40,2220);
out.seekp(2*sizeof(e1));
out.write((char*)&e5,sizeof(e5));
out.close();
ifstream in("Employee.txt",ios::in|ios::binary);
Employee s1;
cout<<"\n-------從檔案中讀出第3個人的資料-----\n\n";
in.seekg(2*(sizeof(s1)),ios::beg);
in.read((char*)&s1,sizeof(s1));
s1.display();
cout<<"\n---------從檔案中讀出全部的資料------\n\n";
in.seekg(0,ios::beg);
in.seekg(0,ios::beg);
while(in.read((char*)&s1,sizeof(s1))){
s1.display();
// in.read((char*)&s1,sizeof(s1));
}
/*char xm[10];
cin>>xm;
ifstream in("Employee.dat",ios::in|ios::binary);
Employee s1;
in.read(reinterpret_cast<char*>(&s1),sizeof(s1));
while(!in.eof()){
if(strcmp(s1.getName(),xm)==0){
s1.display();
}
in.read((char*)&s1,sizeof(s1));
}*/
in.close();
system("pause");
}
uj5u.com熱心網友回復:
加個函式Trim()試試, 把空格截掉。uj5u.com熱心網友回復:
變數呼叫前,未初始化,vc默認用 0xCC 來填充了uj5u.com熱心網友回復:
uj5u.com熱心網友回復:
因為你把數字直接當成char型別存入文本,而沒經過ASCII轉換uj5u.com熱心網友回復:
應該多載write()函式,寫一個結構體write函式是二進制寫入的,寫入的是字符編碼,數字的編碼編碼轉換過來就是亂碼,除非數字也用字符表示。uj5u.com熱心網友回復:
為name賦值以前,先用memset(name, 0x0, sizeof(name))清空一下。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/94403.html
標籤:基礎類
上一篇:C++程式,需要大神,急!!!
下一篇:Dnotes 編譯問題
