在学校,我们正在学习如何在 Visual Studio 中使用 c++ 中的二进制文件。这段代码在 Visual Studio 2005 中完美运行,但在 2010 - 2013 版本中却不行。它给出了一个读数违规错误。所以我希望你们中的一个可以帮助我,因为即使我的老师也不知道出了什么问题:(错误发生在阅读的最后。我尝试了不同的 ifstream 和 ofstream 方法,但没有成功。
我的代码:
#include <z:/Yoshi On My Mac/Google Drive/School/2013-2014/C-taal/headeryoshi.h>
#define B "z:/Yoshi On My Mac/Google Drive/city.dat"
typedef struct city {
string zip, name;
};
void add() {
ofstream file;
city city;
titelscherm("ADD CITY");
cout << "ZIP: ";
getline(cin, city.zip);
while (city.zip not_eq "0") {
cout << "Name: ";
getline(cin, city.name);
file.open(B, ios::app | ios::binary);
file.write((char*)&city, sizeof(city));
file.close();
titelscherm("ADD CITY");
cout << "POSTCODE: ";
getline(cin, city.zip);
}
cout << "city: ";
file.close();
}
void read() {
ifstream file;
city city;
titelscherm("READ CITY");
file.open(B, ios::in | ios::binary);
file.read((char*)&city, sizeof(city));
while (!file.eof()) {
cout << city.zip << " ";
cout << city.name << endl;
file.read((char*)&city, sizeof(city));
}
file.close();
_getch();
}
void search() {
string zip;
city city;
ifstream file;
bool find;
titelscherm("SEARCH ZIP");
cout << "ZIP: ";
getline(cin, zip);
file.open(B, ios::in | ios::binary);
if (!file.is_open()){
cout << "FILE ERROR";
}
else {
do {
file.read((char*)&city, sizeof(city));
find = (city.zip == zip);
} while (!file.eof() and !find);
if (find) {
cout << city.name << endl;
}
else {
cout<<" zit niet in het file" << endl;
}
}
_getch();
file.close();
}
int main() {
add();
read();
search();
return 0;
}