views:

63

answers:

5

As the question says am trying to parse one of the elements of an string array into a int variable. although the code is right in terms of syntax, when I try to run it, I get the following error message.

Error 1 Building content threw FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at TileContent.Tiles.TileLayerProcessor.Process(XmlDocument input, ContentProcessorContext context) in C:\Users\Darren\Documents\Enders\TileContent\Tiles\TileLayerProcessor.cs:line 75

here is the code that is causing the problem below

                foreach (string line in lines)
                {
                    string realLine = line.Trim();

                    if (string.IsNullOrEmpty(line))
                      continue;

                    string[] cells = realLine.Split(' ');

                    for (int x = 0; x < width; x++)
                    {
                        int cellIndex = int.Parse(cells[x]);

                        layer.Layout[row, x] = cellIndex;
                    }
A: 

The error occurs because cells[x] cannot be parsed as an Int32. Try debugging and inspecting cells after string[] cells = realLine.Split(' ');

Winston Smith
A: 

You say you are trying to parse one of the elements, but your for loop is parsing all of the elements.

Provide us with the value of your lines variable, and then it would be much easier to understand what you are trying to do.

Additionally, you can use int.TryParse() to determine whether the value is in an int or not, without throwing an error..

RedFilter
A: 

It's difficult to say without seeing the input, but assuming all the lines contain only valid int values, I would guess that there is more than one space separating the numbers in the line. In this case, the array returned by Split will contain some empty strings which cannot be converted to int. In this case use:

string[] cells = realLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Lee
A: 

If you use simple int parsing, be sure to provide IFormatProvider identifying the culture source. If you have numbers in culture-invariant form, use following code:

int cellIndex = int.Parse(cells[x], CultureInfo.InvariantCulture);

It will probably not solve your problem now, but it is good to always pass CultureInfo parameter (this will work as a comment as well). BTW. If I were you, I will use TryParse() instead...

Paweł Dyda
+1  A: 

Embarrsingly enough it was due to the tabbing I had done to the information which messed around with how it was being read in.

dbomb101