-1

我在 c# 控制台中的基于文本的 RPG 有一个小问题。

我已经制定了一种保存方法并且有效,但是当我想加载它时,它给了我一个错误..

这是我的加载代码:

(字符串没有给出错误,但问题从 Level 到 Agility 开始)

代码 :

public static void LoadData ()
{
        // create reader & open file
        TextReader tr = new StreamReader("SavedGame.txt");

        // read lines of text
        string xCoordString = tr.ReadLine();
        string yCoordInt= tr.ReadLine();

        //Convert the strings to int
        Name = Convert.ToString(xCoordString);
        PlayerType = Convert.ToString (xCoordString);
        Level = Convert.ToString(xCoordString);
        HP = Convert.ToInt32(yCoordInt);
        Strenght = Convert.ToInt32(yCoordInt);
        Intelligence = Convert.ToInt32(yCoordInt);
        Agility = Convert.ToInt32(yCoordInt);
        // close the stream
        tr.Close();
}
4

5 回答 5

0

您没有正确解析保存文件。如果这是您保存文件的格式:

Stefano 
Knight 
1 
100 
3 
3 
3

那么您将需要迭代地读取每一行并将读取的值解析到您的变量中,如下所示:

string line = string.Empty;

//Convert the strings to int
line = tr.ReadLine();
Name = line;
line = tr.ReadLine();
PlayerType = line;
line = tr.ReadLine();
Level = Convert.ToInt32(line);
line = tr.ReadLine();
HP = Convert.ToInt32(line);
line = tr.ReadLine();
Strenght = Convert.ToInt32(line);
line = tr.ReadLine();
Intelligence = Convert.ToInt32(line);
line = tr.ReadLine();
Agility = Convert.ToInt32(line);

当然有更好的方法来管理你的保存文件数据,但这应该告诉你为什么你的解析不起作用。

于 2013-11-14T20:01:30.987 回答
0

您可以像这样遍历这些行,但是您需要确定它是哪个属性并相应地对待它。

 TextReader tr = new StreamReader("SavedGame.txt");


 string charInfo;
 while ((charInfo = tr.ReadLine()) != null)
 {
     //parse the line and put into appropriate variable.
 }
于 2013-11-14T20:01:50.723 回答
0

读入变量的任何内容都不能转换为 int。您可能必须去除换行符/回车符,或者简单的数据不是数字。在尝试转换它之前,您应该对其进行测试和/或清理。

于 2013-11-14T19:44:35.390 回答
0

我不知道你在做什么

           string xCoordString = tr.ReadLine();
            //Convert the strings to int
           Name = Convert.ToString(xCoordString);

为什么你的字符串转换成字符串???

所以你读 string ,那么你应该拆分它

           string[] s = xCoordString .Split(' ');

然后

           var firstVariable=s[0];
           var secondVariable=s[1];

等等。这应该可以帮助您 使用 C# 拆分字符串?

还有一个:使用

        int.Parse(string value)  

希望我的回答对您有所帮助。祝你好运 !

于 2013-11-14T19:45:56.057 回答
0

您可能希望使用它TryParse(String, Int32)来检查解析是否成功,如果解析不成功,则执行一些操作(如设置默认值或通知用户)。

您可以清理输入字符串然后解析它:

private static int ParseNumber(string input)
{
             string cleanedInput = input.Where(c => char.IsDigit(c)).ToString();
             int result;
             if (!Int32.TryParse(cleanedInput, out result))
             {
                Console.WriteLine("An error occured..");
             }
     return result;

}

只需使用Agility = ParseNumber(input).

于 2013-11-14T19:47:46.040 回答