0

Here's the issue; I'm trying to readline's from a .txt, however there are blank lines inbetween each number, so it's throwing me an error and filling the rest of my array with the default 0's. should I be using trim before parsing?

(this was on a c# final, and my instructor may or may not go over the final answer so I am asking here out of curiosity, my solution was to edit the .txt file so there were no empty lines. lol.)

    private void getScoreButton_Click(object sender, EventArgs e)
    {
        double sum = 0.00;
        double avg = 0.00;
        int numBelowAvg = 0;
        int numAboveAvg = 0;
        const int SIZE = 20;
        StreamReader inputFilesData;
        int i = 0;

        int[] scores = new int[SIZE];

        try
        {
            inputFilesData = File.OpenText("scores.txt");

            while (i < scores.Length && !inputFilesData.EndOfStream)
            {
                scores[i] = int.Parse(inputFilesData.ReadLine());
                i++;
            }
            inputFilesData.Close();

        }
        catch (Exception excep)
        {
            MessageBox.Show(excep.Message);
        }


        for(int j= 0; j <scores.Length; j++)
        {
            scoreListBox.Items.Add(scores[j]);
            sum += scores[j];
        }

        avg = sum / scores.Length;

        for (int j = 0; j < scores.Length; j++)
        {
            if(scores[j]>avg)
            {
                numAboveAvg++;
            }
            else
            {
                numBelowAvg++;
            }
        }

        avgLabel.Text = avg.ToString("N2");
        aboveAvgLabel.Text = numAboveAvg.ToString();
        belowAvgLabel.Text = numBelowAvg.ToString();

        

    }
}

}

Slayer
  • 1
  • There are lots of possible ways. See `int.TryParse()`, per duplicate, for example. That said, only your instructor can really answer the question. They presumably provided the file, so they also presumably have some specific technique in mind you're expected to use in order to deal with the blank lines. If the lines are consistently blank, one option is to just always read two lines at a time, but parse just the one with the number in it. – Peter Duniho Dec 07 '20 at 22:07
  • for some reason, can't post answer, you can try this while (i < scores.Length && !inputFilesData.EndOfStream) { string line; while ((line = inputFilesData.ReadLine()?.Trim()) != null){ // skip empty lines and comments if (string.IsNullOrWhiteSpace(line)) continue; } scores[i] = int.Parse(line); i++; } – Nonik Dec 07 '20 at 22:14

1 Answers1

0

You could exclude blank lines using something like:

while (i < scores.Length && !inputFilesData.EndOfStream)
{
    String line = inputFilesData.ReadLine().Trim();
    if (line.Length > 0)
    {
        scores[i] = int.Parse(line);
        i++;
    }
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40