I have made a small and very simple console game with C++, but now I want it to save the score to a .txt file. That's not so hard, but when I want it to check whether the new high-score is higher than the previous one from the .txt file I get stuck... The real problem is that I don't know how to save (or extract) the numerical value of the score in a .txt file instead of the numbers (so, for example, I want to save or extract the value 34 instead of just the characters 3 and 4). If I can do this, I can then compare the value from the file with the score the player achieved in his current playthrough and print out the difference.
Just to clarify:
If there is no file: create it and save the score.
If there is a file: read it, compare the read value (the old score) with the new score, print the difference to the screen and save the new score to the .txt file and close it.
It works alright now, it saves the new highscore, but I still can't get it to check whether the score in the txt file is higher than the current score.
What I have so far:
(side note: the score in my program is equal to the level of the player, hence playerlvl)
Given that you are saving the value playerlvl to file, and then reading that value back in and comparing it to the value playerlvl, how could it be lower or higher than playerlvl? It's the same value, and you have no case
That's true, but I named the read value highscore so that I'd avoid this problem, now I'm just comparing the read value highscore from the file with the achieved score playerlvl, right?
You should open the file and read in the score to check it BEFORE you write to the file. What if you just overwrite the high score with a score of 0? And because you read it immediatly after writing it, how can it have changed? Do you think someone is going to open, edit, and save the file between lines 5 and 7? ;)
I'm just comparing the read value highscore from the file with the achieved score playerlvl, right?
Given that you know for an absolute fact that the value in the file IS the exact same value as playerlvl, because lines 3 to 5 of your do that, you know for an absolute fact that the the value you read from file is the same as playerlvl.
The problem isn't your code - it's how you're solving the problem. You've got a number, playerlvl, and then you're writing that number down, and then you're comparing the number you just wrote down with playerlvl. See the problem?