从txt文件中读取字符串和int? [英] Reading string and int from a txt file?

查看:53
本文介绍了从txt文件中读取字符串和int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个排行榜,但这就是我到目前为止的情况,我有点卡住了。

I'm trying to create a leaderboard, but here's what I have so far and I'm a bit stuck.

class utilizeLeaderboard
    {

        string mode;
        bool gameover;

        string playername;
        int playerscore;

        StreamReader sreader;
        StreamWriter swriter;

        List<string> playernames = new List<string>();
        List<int> playerscores = new List<int>();
         //Not sure why it doesn't have a type, just followed an example.
        ArrayList highlist = new ArrayList();
        


        public utilizeLeaderboard(string name, int score)
        {
            //new information to be supposedly added to highlist to be sorted with the rest of the stored scores (from the .txt file)
            playername = name;
            playerscore = score;



        }

        public void setType(string s)
        {
            mode = s;
            gameover = true;
        }

        void loadScores()
        {
            switch (mode)
            {
                case "Endless":
                    sreader = new StreamReader(@"C:\Users\Endless.txt");
                    //load player names
                    //load player scores
                    //add to highlist to be sorted together with the newly added info - playername & playerscore
                    break;
                case "Timed":
                    sreader = new StreamReader(@"C:\Users\Timed.txt");
                    break;
                case "Moves":
                    sreader = new StreamReader(@"C:\Users\Moves.txt");
                    break;
                    
            }
        }

        void evaluateScores()
        {
            //sort highlist

            playernames.Add(playername);
            playerscores.Add(playerscore);

            for (int u = 0; u < playernames.Count; u++)
            {
                //Not sure yet how this part works, just followed an example. 
                //Maybe some kind soul can explain how it works?
                highlist.Add(new utilizeLeaderboard(playernames[u], playerscores[u]));
            }
        }

        void writeScores()
        {
            //write sorted highlist to .txt file

            switch (mode)
            {
                case "Endless":
                    swriter = new StreamWriter(@"C:\Users\Endless.txt");
                    //load player names
                    //load player scores
                    //add to highlist to be sorted together with the newly added info - playername & playerscore
                    //for (int u = 0; u < highlist.Count; u++)
                    //{
                    //    swriter.Write(playernames[u]+ " " + playerscores[u] + Environment.NewLine);
                    //}
                    break;
                case "Timed":
                    swriter = new StreamWriter(@"C:\Users\Timed.txt");
                    break;
                case "Moves":
                    swriter = new StreamWriter(@"C:\Users\Moves.txt");
                    break;

            }
        }
        
    }





1.将如何我对分数进行排序,但确保每个分数都没有丢失拥有它的玩家的名字?

2. Java有 hasNext()可以用来检查你是否到达了最后一行, read.Next()只读取字符串和 read.NextInt()仅用于读取int。它们在C#中的等价物是什么?我将使用它们来读取.txt文件中的分数,因为txt文件中的信息格式如下:

John 23

Anne 29

Peter 21

3.你能否就程序如何从高到低排序得分的一些提示?

4.为什么highlist没有类型?对不起,这听起来很愚蠢,我只是按照一个例子。

5.如果我的某些假设出错了,请随意指出它们。 :)



1. How will I sort the scores but making sure that each score doesn't lose the name of the player owning it?
2. Java has the hasNext() which can be used to check if you have reached the last line,read.Next() for reading only string and read.NextInt() for reading only int. What are their equivalents in C#? I will be using them to read the scores from the .txt file, as the format of the information in the txt file will be like this:
John 23
Anne 29
Peter 21
3. Can you drop a few hints on some possible ways on how the program can sort the scores from highest to lowest?
4. Why doesn't highlist have a type? Sorry that sounds stupid, I just followed an example.
5. If ever I'm wrong in some of my assumptions, feel free to point them out. :)

推荐答案



我发现使用文本文件存储可序列化的数据有点奇怪。

为什么不使用XML文件作为例子并利用.Net类的OO功能。

我相信在你的情况下使用它会更方便。 />


无论如何为了分类目的我发现这篇文章很有用,希望它可以帮到你:



在C#中排序算法 [ ^ ]


重新提出问题标题中的问题:



1.假设分隔符是逗号。



2.说明一些基本的错误检查并报告,使用'throw等,但绝不彻底检查文件读取正确性。
Re the issue asked about in the title of the question:

1. Assumes the delimiter character is a comma.

2. illustrates some elementary error-checking and reporting, use of 'throw, etc. but, by no means thoroughly checks the file being read for correctness.
private Dictionary<string, int> PlayerHighScores = new Dictionary<string, int>();

// for testing only
private string baseFilePath = @"C:\Users\Uruk\Desktop\";

// for testing only
private string mode = "Endless";

private void loadScores()
{
    // clear the Dictionary
    PlayerHighScores.Clear();

    // to use in splitting lines in the file
    char[] splitChars = new char[] {','};

    // to hold the result of splitting the line
    string[] splitLine = new string[2];

    string line;

    int testInt = 0;

    // should you check to make sure the value of 'mode is valid here
    // and throw an error if it is not valid ?

    using (StreamReader sReader = new StreamReader(baseFilePath + mode + ".txt"))
    {
        int lineCount = 0;

        while (! sReader.EndOfStream)
        {
            lineCount++;

            line = sReader.ReadLine();

            try
            {
                splitLine = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);

                string playerName = splitLine[0];

                // valid score data ?
                if (! Int32.TryParse(splitLine[1], out testInt))
                {
                    throw new ArgumentException(message: "bad entry for score in line: " + lineCount.ToString());
                }

                // add the new data to the Dictionary
                PlayerHighScores.Add(splitLine[0], testInt);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Invalid line in High Score file in line:" + lineCount.ToString());
            }
        }
    }
}

以下是使用Linq返回从最高到最低排序分数的演示:

Here's a demonstration of using Linq to return the scores ordered from highest to lowest:

List<int> highScores = PlayerHighScores.Values.OrderByDescending(s => s).ToList();


1。您可以使用词典存储用户得分,其名称为键,得分为值。



对于存储操作检查以下链接或尝试使用googling对字典对象进行排序操作。



http://www.dotnetperls.com/sort-dictionary [

title =新窗口> ^
]
1. You can use Dictionary for storing user score with their name as keys and scores as values.

For Storing operation check below link or try googling for sorting operation on dictionary object.

http://www.dotnetperls.com/sort-dictionary[
title="New Window">^
]


这篇关于从txt文件中读取字符串和int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆