首页 > 解决方案 > 从文件读取后,数组包含“垃圾”值

问题描述

我有一个名为“topboard”的数组,它从“topboard.txt”读取数据,但在读取后它包含垃圾值。在“topboard.txt”中,我保留了制作 Snake 游戏的前 10 分,所以“topboard.txt”看起来像这样(每个分值都应该从新行开始):560 470 300 ...我需要把所有我在 cpu 上的数组中的那些值。我写的代码:

void stopGame() {
    gameOver = true;
    int topboard[11];

    // Writed last score in 11 line
    ofstream fileOutputStream;
    fileOutputStream.open("topboard.txt");
    fileOutputStream << endl << score;
    fileOutputStream.close();

    // read whole file to topboard[]
    ifstream inputFileStream;
    inputFileStream.open("topboard.txt");
    for (int i = 0; inputFileStream.eof(); i++) {
        inputFileStream >> topboard[i];
    }
    inputFileStream.close();
    
    // do some sorting stuff here

    // writed back new (sorted) topboard
    fileOutputStream.open("topboard.txt", ios_base::trunc);
    for (int i = 0; i < 10; i++) {
        fileOutputStream << topboard[i];
    }
    fileOutputStream.close();

};

我的输出:

-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460

标签: c++filesystemsfstreamifstream

解决方案


推荐阅读