简体   繁体   English

C#从文本文件加载数据

[英]C# loading data from text file

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. 假设你买了一把斧头,这是70个硬币。 You start with 100 coins, so you're left with 30 coins. 您从100个硬币开始,所以剩下30个硬币。 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. 您返回并加载保存的游戏,您有49个硬币和48个健康点。

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. 我不知道它从哪里得到49和48的值。

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? 难道我做错了什么?

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 . 第一次通过循环,行为"100" ,因此line[0] 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. 这是一个'1'char ,而不是值1,所以player.gold = line[0]转换为将player.gold设置为字符'1'的数字等效,即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]);

r is a string, not an array of lines. r是一个字符串,而不是一个行数组。 you're trying to set gold to the first character of the first line, and health to the second character, etc. 你试图将黄金设置为第一行的第一个字符,将健康设置为第二个字符,等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM