0

I have a function like this:

   List<float> myList = new List(float);

     public void numbers(string filename)
    {
        string input;
        float number;

        if (System.IO.File.Exists(filename) == true)
        {
            System.IO.StreamReader objectReader;
            objectReader = new System.IO.StreamReader(filename);

            while ((input = objectReader.ReadLine()) != null)
            {
                number = Convert.ToSingle(input);
                myList.Add(number);
            }
            objectReader.Close();
        }
        else
        {
            MessageBox.Show("No Such File" + filename);
        }
    }

Where Im trying to add numbers (floats) from a text file into a List. But I keep getting errors saying wrong format. The numbers in the text file are one number per line...any help?

1
  • can you post a snippet of your text file. There might be some bad characters in it. According to msdn, ReadLine doesnt return the carriage return,line feed. Commented Dec 11, 2009 at 2:42

6 Answers 6

4

I would suggest you do a Trim call like this

number = Convert.ToSingle(input.Trim());

However, a better code would be using a TryParse call

float tmp;
if(float.TryParse(input.Trim(), out tmp)
{
   mylist.Add(tmp);
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Though tryParse (appears) to work happily without the .trim()
3

Your code worked fine for me except for the case of a newline (and of course for entries that were not numbers at all)

Here is a version that should work for you, using a tryParse to check if each line can convert to a single):

    public void Numbers(string filename)
    {
        List<float> myList = new List<float>();     

        string input;

        if (System.IO.File.Exists(filename) == true)
        {
            System.IO.StreamReader objectReader;
            objectReader = new System.IO.StreamReader(filename);
            while ((input = objectReader.ReadLine()) != null)
            {
                Single output;
                if (Single.TryParse(input, out output ))
                {
                    myList.Add(output);
                }
                else
                {
                   // Huh? Should this happen, maybe some logging can go here to track down why you couldn't just use the .Convert()
                }
            }
            objectReader.Close();

        }
        else
        {
            MessageBox.Show("No Such File" + filename);
        }
    }

As Mike C rightly points out, this could be potentially risky - swallowing good data that has been corrupted by the output process. The tryParse method returns false when it fails so you could add in an else branch and some logging to check just what is causing the failures and see if there is another bug floating around that can be corrected.

2 Comments

Yes, but what are you leaving out? Spaces? Alpha characters? Perhaps this is a sign of something incorrect in whatever process generates the source file. Are you sure you want to blindly exclude anything that is not a number? To me, this is similar to swallowing an exception.
@Mike C very true comment. I've added a little bit to my answer talking about that.
0

Do you have any blank lines in the file, or failures to convert the number? My guess is that you have a line which is not castable to float from its current format. You should make sure you sanitize the lines before reading them in (strip off everything that is not a number using a regex) and throw the line out if it fails the check.

One thing you might do is use double instead and do a Convert.ToDouble().

Comments

0

Are there spaces or commas or anything? The best thing to do would be to set a breakpoint on

number = Convert.ToSingle(input);

to see what input is actually before you try to convert it.

1 Comment

What happens if you press F5? Does it immediately fail, or do you hit the same breakpoint again?
0

There's a wonderful free package called FileHelpers which helps with importing data from all sorts of text files. The advantage with this is that a lot of the deeper error handling is already in place.

Comments

0

By the way, if (System.IO.File.Exists(filename) == true) can be shortened to if (System.IO.File.Exists(filename))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.