【发布时间】:2021-01-30 12:10:42
【问题描述】:
在向文件写入内容之前,我想进行一些检查。当我进行这些检查时,写作不起作用。这可能是什么原因?
检查过程是这样的。文件中是用户输入的数据吗? 如果有更简单的方法来检查,我也可以试试。
工作代码:
void add_dealer(){
file.open("center.txt", ios::out|ios::app);
c.new_Dealer();
file.write((char*)&c,sizeof(Center));
file.close();
cout << "The dealer has been saved.";
}
检查后:
fstream file;
bool check_dealer_name(string name){
bool result = false;
file.open("center.txt", ios::in);
while(file.read((char*)&c,sizeof(Center))){
if(c.getLocation()== name){
result = true;
}
}
return result;
}
bool check_dealer_id(int id){
bool result = false;
while(file.read((char*)&c,sizeof(Center))){
if(c.getID() == id){
result = true;
}
}
return result;
}
void add_dealer(){
c.new_Dealer();
file.open("center.txt", ios::out|ios::app);
if (!check_dealer_id(c.getID()) || !check_dealer_name(c.getLocation())){
file.write((char*)&c,sizeof(Center));
file.close();
cout << "The dealer has been saved.";
}
else{
cout << "This Dealer name or dealer id already exists" << endl;
}
file.close();
}
类:
class Center{
int ID;
char location[50];
public:
void new_Dealer(){
cout << "Enter the Dealer ID: " ;
cin >> ID;
cout << endl << "Enter the Dealer location: ";
cin >> location;
}
【问题讨论】:
-
不能像这样读写对象,必须序列化和反序列化。
-
@spectras 这不是真的。看类定义,二进制读写完全没问题。
-
@john> 我读得有点快,确实那个特定的类应该可以工作。不过,这样很容易得到不可用的文件。