c ++将文件读入struct

时间:2014-04-07 02:44:42

标签: c++ ifstream cin

在终端中运行时,执行以下代码时会出现分段错误。在Xcode中,它也没有工作,但它让程序继续,我只是假设它是一个文件路径问题。我做错了什么想法?调用createPuzzleList时会出现问题。

enum attribute_t {MONEY, TIME, INTEL};
enum action_t {PENALTY, REWARD};
const ushort MAX_NUM_ACTIONS = 3;

struct action {
    action_t actType;
    attribute_t attType;
    ushort points;
};
struct puzzle {
    string question;
    string key;
    ushort numActions;
    action actionArray[MAX_NUM_ACTIONS];
    puzzle* nextPuzzle;
};

typedef puzzle* puzzlePtr;

struct puzzleDB {
    ushort numberOfPuzzles;
    puzzlePtr puzz;
};

int createPuzzleList(puzzleDB& puzzles, string filename) {
    ifstream inStream;
    inStream.open((char*)filename.c_str());
    if (inStream.fail()) {
        cout << "Input file opening failed." << endl;
        return 1;
    }
    string actType;
    string attType;
    ushort points;
    puzzlePtr cur;
    while (!inStream.eof()) {
        inStream >> puzzles.puzz->question;
        inStream >> puzzles.puzz->key;
        inStream >> puzzles.puzz->numActions;
        for (int i = 0; i < puzzles.puzz->numActions; i++) {
            action act;
            inStream >> actType;
            if (actType == "PENALTY") { act.actType = PENALTY;}
            else {act.actType = REWARD;}
            inStream >> attType;
            if (attType == "MONEY") {act.attType = MONEY;}
            else if (attType == "TIME") {act.attType = TIME;}
            else {act.attType = INTEL;}
            inStream >> points;
            act.points = points;
            puzzles.puzz->actionArray[i] = act;
        }
        puzzles.puzz = puzzles.puzz->nextPuzzle;
        puzzles.numberOfPuzzles++;
    }
    inStream.close( );
    return 0;
}

1 个答案:

答案 0 :(得分:0)

Q值。 puzzles.puzz在哪里初始化? A.无处。因此它无处可寻,因此通过puzzles.puzz->question和朋友引用它会给你一个SIGSEGV。