9

I'm writing a program for school so I don't outright want someone to fix it for me, but if someone could point out where they see the error, that would be really helpful! :D

The program is supposed to take in a series of numbers in a text box, with the user pressing enter after each integer entry, when they press enter, the number writes to a file, so that each number is separated by a comma. When the user hits the Done button, the button and textbox become disabled, then a new button and a list box become enabled. The user can select the results button to see in the list box the frequency of the numbers that were entered in the text box.

I feel that most of it is working properly except that it doesn't actually write to the file. This is only my first year so I'm fairly new at this, but from what information I have it all looks right.

If someone could point out where I should be looking for an error, again, I'd really appreciate it! Here's my code:

 using System;
    using System.Collections.Generic;
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;

    namespace StudentPoll1
    {
    public partial class Form1 : Form
    {
        const string FILENAME = "numbers.txt";
        FileStream file = new FileStream(FILENAME,
            FileMode.Create, FileAccess.ReadWrite);        

        public Form1()
        {            
            InitializeComponent();
            btnResult.Enabled = false;
        }

        private void tbInput_KeyDown(object sender, KeyEventArgs e)
        {
            const char DELIM = ',';
            int input;
            const int MIN = 1;
            const int MAX = 10;

            int.TryParse(tbInput.Text, out input);
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    if (input < MIN || input > MAX)
                    {
                        MessageBox.Show("Please enter an integer between 1 and 10");
                    }
                    else
                    {
                        StreamWriter writer = new StreamWriter(file);
                        writer.WriteLine(input + DELIM + " ");
                    }
                }
                catch (IOException)
                {
                    MessageBox.Show("Error with input");
                }
                finally
                {
                    tbInput.Clear();
                }
            }
        }

        private void btnDone_Click(object sender, EventArgs e)
        {
            file.Close();
            btnDone.Enabled = false;
            btnResult.Enabled = true;
            lbOutput.SelectionMode = SelectionMode.None;
        }

        private void btnResult_Click(object sender, EventArgs e)
        {            
            int[] ratings = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int[] results = new int[10];
            int entry;
            const char DELIM = ',';
            FileStream fs = new FileStream(FILENAME,
                FileMode.Open, FileAccess.Read);
            StreamReader reader = new StreamReader(fs);
            string record;
            string[] fields;
            record = reader.ReadLine();
            while (record != null)
            {
                fields = record.Split(DELIM);
                entry = Convert.ToInt32(fields[0]);
                foreach (int x in ratings)
                {
                    if (entry == ratings[x])
                    {
                        ++results[x];
                    }
                }
            }
            for (int num = 0; num < ratings.Length; ++num)
            {
                lbOutput.Items.Add(ratings[num] + "    " + results[num]);
            }
            fs.Close();
            reader.Close();
        }
    }
}
ArK
  • 20,698
  • 67
  • 109
  • 136

3 Answers3

3

StreamWriter (and StreamReader) are buffered. IO operations are typically much slower than working in memory so files are often read and written in chunks.

If you only write a small amount using a StreamWriter you'll get the behaviour you can see here.

The information you have written has been written to the StreamWriters buffer, it won't appear on disk until you either Flush the buffer or close the stream.

James
  • 9,774
  • 5
  • 34
  • 58
  • The flush worked writing the number to the file, I also had to convert the input to a string because it was showing the character values instead of the numbers. Now the array at the bottom is going out of range, though – Melissa Grouchy Apr 16 '15 at 12:36
  • 1
    @MelissaGrouchy Array's are 0 based and you're index is 1 based. This means that results[1] accesses the second element on the array and results[10] accesses the 11th element, which doesn't exist. – James Apr 16 '15 at 12:46
  • Oh I see what you mean! I'll try messing around with that and see where it gets me. Thanks! – Melissa Grouchy Apr 16 '15 at 13:11
1

I recommend you to use "using" for streamwriter. if you write multiple files it's proper to close them at the end.

Using. The using statements in the examples open and prepare the files. At the end of the statements they close and dispose of the resources. If your program does lots of writes, it will manage system resources correctly if you use using.

here you find a basic tutorial. http://www.dotnetperls.com/streamwriter

Kjenos
  • 529
  • 2
  • 5
  • 19
0

Okay, so what I fixed here to get it to work was:

As advised, I added Flush(); after writing the the file.

I changed my foreach loop to a for loop to initialize the x variable to 0, because it was starting off at 1.

I also added the statement

record = reader.ReadLine(); 

inside the forloop so that it was reading the next number in the file after checking the previous one.

I'm sure there are some other things I could add or change to make more efficient, but I am fairly new to all of this, and this is what my course requires me to do. If you would still want to mention some of those changes to help other people who might look at this later on, feel free :)

Thank you for your posts! I appreciate the help! Cheers!