尝试在C#中读取和显示文本文件到控制台时遇到麻烦 [英] Having troubles trying to read and display a text file to the console in c#

查看:79
本文介绍了尝试在C#中读取和显示文本文件到控制台时遇到麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用控制台应用程序以c#编写琐事游戏。而且我很难让控制台读取文件。目前,它的作用是无法读取文件,并且索引不在数组的范围内。但是,随后将显示文本文件中的所有内容。我不确定我得到的文件无法读取,但随后显示该文件。

I am trying to make a trivia game in c# using a console application. And I am having troubles getting the console to read the file. Currently what its doing is saying that the file could not be read and the the index was outside the bounds of the array. But then everything that is in the text file gets displayed. I am unsure on what I get the file could not be read but then the file gets displayed.

该文件是.txt文件,这是下面的样子

The file is a .txt file and here is what is looks like

What is another name for SuperMan?,the man of steel
What is Superman's only weakness?,kryptonite
What is the name of Batman's secret identity?,bruce wayne
Batman protects what city?,gotham city
How did Spiderman get his superpowers?,bitten by a radioactive sipder
This superheros tools include a bullet-proof braclets and a magic lasso.Who is she?,wonder woman
Which superhero has an indestructible sheild?,captain america
Which superhero cannot transformback into human form?,the thing
What villan got his distinctive appearance form toxic chemicals?,joker
What is the name of the archnemesis of the Fantastic Four?, dr doom

这是我用于读取和显示文件的代码。

Here is the code that I have for reading and displaying the file.

static void Main(string[] args)
    {
        string filename = @"C:\Trivia\questions.txt";
        List<string> questions = new List<string>();
        List<string> answers = new List<string>();

        LoadData(filename, questions, answers);

        Console.WriteLine();
        questions.ForEach(Console.WriteLine);
        Console.WriteLine();
        answers.ForEach(Console.WriteLine);
    }

    static void LoadData(string filename, List<string> questions, List<string> answers)
    {
        try
        {
            using(StreamReader reader = new StreamReader(filename))
            {
                string line;

                while((line = reader.ReadLine()) != null)
                {
                    string[] lineArray = line.Split(',');
                    string annswer = lineArray[1];
                    string question = lineArray[0];
                    questions.Add(question);
                    answers.Add(annswer);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("File could not be read");
            Console.WriteLine(e.Message);
        }
    }

这是控制台上的输出。

File could not be read
Index was outside the bounds of the array.

What is another name for SuperMan?
What is Superman's only weakness?
What is the name of Batman's secret identity?
Batman protects what city?
How did Spiderman get his superpowers?
This superheros tools include a bullet-proof braclets and a magic lasso.Who is she?
Which superhero has an indestructible sheild?
Which superhero cannot transformback into human form?
What villan got his distinctive appearance form toxic chemicals?
What is the name of the archnemesis of the Fantastic Four?

the man of steel
kryptonite
bruce wayne
gotham city
bitten by a radioactive sipder
wonder woman
captain america
the thing
joker
dr doom

感谢您的建议

推荐答案

我怀疑文件末尾有一个空行(或至少没有逗号的行),然后这行: string annswer = lineArray [1]; 引发异常,因为您已经硬编码了索引 1 ,而不先检查 lineArray 的大小。然后显示错误,但仅在填充了问题和答案之后,您才能在控制台上看到这些输出。

I suspect that there's a blank line (or at least a line without a comma) at the end of the file, and then this line: string annswer = lineArray[1]; is throwing an exception because you've hard-coded index 1 without first checking the size of the lineArray. Then the error is shown, but only after the questions and answers have been populated, so you also see those output to the console.

为避免这种情况,这是一个很好的选择实践是在检查数组索引之前确保它存在。这样的事情可能会有所帮助:

To avoid this, it's a general good practice is to ensure that an array index exists before checking it. Something like this might be helpful:

while ((line = reader.ReadLine()) != null)
{
    string[] lineArray = line.Split(',');

    // If this line doesn't contain a comma, then skip it
    if (lineArray.Length < 2) continue;

    string annswer = lineArray[1];
    string question = lineArray[0];
    questions.Add(question);
    answers.Add(annswer);
}

或者,您可以抛出异常:

Alternatively, you could throw an exception:

// If this line doesn't contain a comma, throw an exception
if (lineArray.Length < 2)
{
    throw new FormatException($"This line does not contain a comma: {line}");
}






另外,您可以简化您可以使用 System.IO.File 类来读取文件:

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    try
    {
        foreach (var line in File.ReadLines(filename))
        {
            var lineArray = line.Split(',');

            // If this line doesn't contain a comma, skip it
            if (lineArray.Length < 2) continue;

            questions.Add(lineArray[0]);
            answers.Add(lineArray[1]);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine($"Error reading file: {e.Message}");
    }
}

这篇关于尝试在C#中读取和显示文本文件到控制台时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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