Search code examples
c++functionfilesavefstream

(C++) What is the issue with my saveGame() function? When I call the function, nothing within it runs but there is no error?


I have tried almost everything, yet I can't figure out why this function won't do anything when I call it. The function is called properly: saveGame(hscore, selectedSaveSlot); (hscore and selectedSaveSlot have been properly defined as ints as well). Additionally, this function is called within another function, within a switch statement. Does anyone have any ideas as to why it won't work?

(i.e. When this function is called the cout doesn't say anything and no save file is created, the code simply skips over it and continues to run seamlessly).

void saveGame(int highscore, int saveSlot) {        
ofstream saveFile1;
ofstream saveFile2;
ofstream saveFile3;
switch (saveSlot) {  
case '1':

    saveFile1.open("SaveFile1.txt", ios::out);



        saveFile1 << highscore;//writing highsore to a file

        saveFile1.close();
        cout << "Your game has been saved successfully!" << endl;
        delayScroll(10, 50);

        break;
case '2':
    saveFile2.open("SaveFile2.txt", ios::out);



        saveFile2 << highscore; //writing highsore to a file

        saveFile2.close();
        cout << "Your game has been saved successfully!" << endl;
        delayScroll(10, 50);

        break;
case '3':
    saveFile3.open("SaveFile3.txt", ios::out);



        saveFile3 << highscore; //writing highsore to a file

        saveFile3.close();
        cout << "Your game has been saved successfully!" << endl;
        delayScroll(10, 50);

        break;
    }
inMenu = true;
}

Solution

  • You are probably calling saveGame with integer 1, 2, 3 etc. However,'1' and 1 are not same. The first one (with quotes around) is a character whose ASCII value is 49, the second one is integer one. Inside the switch you are using character '1', '2', '3'. They will match if you call saveGame(highscore, 49) or saveGame(highscore, 50) or saveGame(highscore, 51) respectively. But they won't match for saveGame(highscore, 1) or saveGame(highscore, 2) or saveGame(highscore, 3).

    In short, these are true:

    '1' != 1
    '2' != 2
    '1' == 49
    

    Change your cases to use actual integers.