0

学校では、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;
}
4

1 に答える 1