0

I have an array called "topboard" which reads data from "topboard.txt", but after reading it contains garbage values. In "topboard.txt" I keep top-10 scores from make Snake game, so "topboard.txt" looks like this (every score value should begin from new line): 560 470 300 ... And I need to put all of those values in my array on cpu. The code I wrote:

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();

};

And the output I have:

-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460-858993460
DaniilV
  • 13
  • 3
  • 1
    You have garbage values because `int topboard[11];` was not initialized, so contains "garbage" and is **undefined behavior** to access. The loop to read in the values in the file does not work, which you'd see if you stepped through the routine with a debugger. – Eljay Nov 10 '21 at 18:04
  • 3
    Help with a future bug: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Nov 10 '21 at 18:05
  • 2
    Change `inputFileStream.eof()` to `! inputFileStream`. Your logic is reversed **and** you want to check for _any_ error condition, not just EOF. – Drew Dormann Nov 10 '21 at 18:06
  • 3
    Or you could do `for (int i = 0; i < 11 && inputFileStream >> topboard[i]; i++) ;` – 001 Nov 10 '21 at 18:06
  • Obligatory: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) Nobody writes perfect code. When your code isn't perfect, this is your first step. It would have found your problem immediately. – Drew Dormann Nov 10 '21 at 18:08
  • I second @JohnnyMopp. As is, your code could attempt to write outside the bounds of the array if someone messed with the file. – sweenish Nov 10 '21 at 18:09
  • Guys, now I've solved my problem. Sorry for such kinda stupid question, but u helped me a lot. Thank u all! – DaniilV Nov 10 '21 at 18:10

0 Answers0