Having troubles trying to read and display a text file to the console in c#

余生长醉 提交于 2020-01-16 12:02:45

问题


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.

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);
        }
    }

Here is the output on the console.

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

Thanks for the suggestions.


回答1:


From playing around with your code, it looks like you might have some newlines at the end of your questions.txt file. Getting rid of those would fix your initial problem, but the real issue is that you're not checking each line to see if it contains a comma, nor are you discarding empty rows of data. Here's an approach that does both:

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    try
    {
        using (StreamReader reader = new StreamReader(filename))
        {
            string[] lines= 
                reader.ReadToEnd() //Read the whole file
                .Trim() //Get rid of whitespace at the beginning and end of the file, no more random newlines at the end.
                .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) //Separate each line AND remove any empty lines.
            ;
            foreach (string _line in lines)
            {
                string line = _line.Trim();
                if (!line.Contains(','))
                {
                    Console.Error.WriteLine("!!! Line did not contain comma for separation");
                    Console.Error.WriteLine("!!!!!! " + line);
                    continue; //Just go on to the next line.
                }
                string[] lineArray = line.Split(',');
                string answer = lineArray[1];
                string question = lineArray[0];
                questions.Add(question);
                answers.Add(answer);
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("File could not be read");
        Console.WriteLine(e.Message);
    }
}

Of course if you want to read each line in separately, just check each line to make sure that it has any length after being trimmed (skip it if not) and that it contains a comma (log the error)




回答2:


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}");
}

Additionally, you could simplify your code slightly by using the System.IO.File class to read the 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}");
    }
}



回答3:


This is one of technique to handle exception.
I've tried your code but it works well.
Apply my code it and look my comment.

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    string readText = ""; //for writing error at catch clause.
    try
    {
        using (StreamReader reader = new StreamReader(filename))
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                readText = line;  //copy text line which is current.

                string[] lineArray = line.Split(',');
                string annswer = lineArray[1];
                string question = lineArray[0];
                questions.Add(question);
                answers.Add(annswer);
            }
        }
    }
    catch (Exception e)
    {
        //print error with problem text.
        Console.WriteLine("File could not be read from : {0}", readText);  
        Console.WriteLine(e.Message);
    }
}

Also, this is another,
Move to : Menu -> DEBUG -> Windows -> Exception settings. And then check "Common Language Runtime Exception". This will allow stop where occur problem. It doesn't matter that is in try~catch clause or not.
This is one of best way to find problem in loop statement.



来源:https://stackoverflow.com/questions/59185967/having-troubles-trying-to-read-and-display-a-text-file-to-the-console-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!