1

私はクロスワード データをバイナリ ファイルに書き込む必要がある cpp で小さなバックエンドを作成しています。すべてのデータ メンバを public にして XWPuzzle クラスを作成しました。xWord はこのクラスのオブジェクトです。バイナリファイルに書き込もうとしているコードは次のとおりです。

#include"binIncludes.h"

int main(int argc, char** argv)
{
    cout<<"Bin read-write Tester\n";
    xWord.title="Yeah!\0";
    xWord.author="Nobody\0";
    xWord.grid=147;
    xWord.userGrid=109;
    xWord.clues[0]="as\0";
    xWord.clues[1]="de\0";
    xWord.clues[2]="re\0";
    xWord.solution[0]="ASSET\0";
    xWord.solution[1]="DEER\0";
    xWord.solution[2]="REED\0";
    xWord.checksum=(int)(xWord.title.at(0))+(int)(xWord.author.at(0))+xWord.grid+xWord.userGrid;
    xWord.checksum+=(int)(xWord.clues[0].at(0))+(int)(xWord.clues[1].at(0))+(int)(xWord.clues[2].at(0));
    xWord.checksum+=(int)(xWord.solution[0].at(0))+(int)(xWord.solution[1].at(0))+(int)(xWord.solution[2].at(0));
    fstream file;
    file.open("binTest.bin",ios::out|ios::binary);
    file.write(SIGNATURE,sizeof(SIGNATURE));
    file.write(VERSION,sizeof(VERSION));
    file.write(TYPE,sizeof(TYPE));
    file.write((char*)xWord.checksum,sizeof(xWord.checksum));
    file.write(xWord.title.c_str(),xWord.title.size());
    file.write(xWord.author.c_str(),xWord.author.size());
    file.write((char*)xWord.grid,sizeof(xWord.grid));
    file.write((char*)xWord.userGrid,sizeof(xWord.userGrid));
    file.close();
    cout<<"File written\n";
    _getch();
    return 0;
}

SIGNATURE、VERSION、および TYPE は null で終了する文字列ですが、コンパイルされたプログラムは行に到達するとエラーをスローします。

file.write((char*)xWord.checksum,sizeof(xWord.checksum));

デバッガーは、MSVCR100.dll で初回例外 (アクセス違反読み取り場所エラー) をスローします。クラスのメンバーを間違った方法で使用して、何か間違ったことをしていますか? これは独立したプロジェクトであり、宿題ではありません。私はこれのために2日間走り回っています。特定のヘルプをいただければ幸いです。ありがとう。

このクラスのデータに加えて、他のデータも書き込む必要があります。

編集:

XWPuzzle.h:

#ifndef XWPULZZLE_H
#define XWPUZZLE_H

#include"binIncludes.h"

class XWPuzzle
{
    public:
        string title;
        string author;
        int grid;
        int userGrid;
        string clues[3];
        string solution[3];
        int checksum;
} xWord;

#endif

binDefines.h:

#ifndef BIN_DEFINES_H
#define BIN_DEFINES_H

#include"binIncludes.h"

#define SIGNATURE "BinFile\0"
#define VERSION "0.1.1\0"
#define TYPE "With Solution\0"

#endif

binIncludes.h:

#ifndef BIN_INCLUDES_H
#define BIN_INCLUDES_H

#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>

using namespace std;

#include"binDefines.h"
#include"XWPuzzle.h"

#endif
4

1 に答える 1

1

整数をポインターにキャストし、このポインターでデータを書き込もうとしています。それは間違っている。チェックサムへのポインターを取得し、キャストしてから書き込む必要があります

file.write((char*)(&xWord.checksum),sizeof(xWord.checksum));

grid および userGrid フィールドと同じ

于 2013-04-08T08:34:18.620 に答える