Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# loading data from text file

Tags:

c#

So I'm trying to load some data from a text file when the user types 'Load'. I have it sort of working, but there's a bug with it, it seems.

Let's say you buy an axe, which is 70 coins. You start with 100 coins, so you're left with 30 coins. You decide to save and exit the game. You come back and load your saved game, and you have 49 coins and 48 health points.

It also does the exact same thing when you save straight away with all the default values. I don't have any idea where it's get the value of 49 and 48 from.

const string f = "savedgame.txt";

        using (StreamReader r = new StreamReader(f))
        {

            string line;
            while ((line = r.ReadLine()) != null)
            {
                player.gold = line[0];
                player.health = line[1];
                Console.WriteLine("Your game has been loaded.");
                menu.start(menu, shop, player, fishing, woodcut, mine, monster, quests, save, load);
            }
        }

This is my text file that I've just saved now.

100
20
1
0
0
5

I've tried examples off Google, but they did the same thing. So I did a bit of research and made one myself.... Did the same thing.

I don't know how much I can show you guys, but I can show more if needed.

Am I doing something wrong?

like image 469
Jon Avatar asked Dec 02 '25 10:12

Jon


1 Answers

There are two problems with your current approach -

First, your logic is currently working on the characters of the first line -

The first time through your loop, line is "100", so line[0] is 1. This is a char of '1', not the value 1, so player.gold = line[0] translates into setting player.gold to the numerical equivelent of the character '1', which is 49.

Second, you're starting a loop and reading line by line, and then doing your work instead of reading all of the lines at once.

You can solve these issues by reading all of the lines at once, and working line by line. Then you also need to convert the entire line to a number, not read one character:

const string f = "savedgame.txt";

var lines = File.ReadAllLines(f);
player.gold = Convert.ToInt32(lines[0]);
player.health = Convert.ToInt32(lines[1]);
like image 146
Reed Copsey Avatar answered Dec 05 '25 00:12

Reed Copsey