My program throws a System.FormatException: "The entrystring has the wrong format."
whenever I am trying run this code:
public double[] ReturnCoordsFromString(string CoordString)
{
string[] cArrStr = CoordString.Split(' ');
List<double> NumList = new List<double>();
foreach (string elem in cArrStr)
{
Console.WriteLine(elem);
double b = Convert.ToDouble(elem); // <= Error is here
NumList.Add(b);
}
double[] retN = NumList.ToArray<double>();
return retN;
}
I have also tried to run it with Convert.ToDouble(elem)
and Encodings with ascii and utf_8. None of these worked.
To understand my code:
I call the function from another function and the CoordString
argument looks like this:
90 10 1000
So they are all Integers, but I need them as double. (I tried Int32.Parse()
and then convert to double, here it crashes on the Int32.Parse()
part)
My code should get the CoordString ("90 10 1000"
) and split it into single strings (["90", "10", "1000"]
).
The Console.WriteLine(elem)
prints the correct numbers, no letters, just numbers as string.
Any idea why / how to fix it? Nothing other questions suggested worked so far.
EDIT:
The weird thing is, printing elem
does work well. But the Exception Window shows me this:
b 0 double
elem "" string
// The class name here
答案 0 :(得分:3)
你可能在某个地方有一个双重空间导致了这个问题。尝试指定StringSplitOptions.RemoveEmptyEntries
:
string[] cArrStr = CoordString(' ', StringSplitOptions.RemoveEmptyEntries)
而不是
string[] cArrStr = CoordString.Split(' ');
此外,您应该使用Double.TryParse
而不是Convert.ToDouble
,因为Double.TryParse
只会在无法转换时返回false,而Convert.ToDouble
会抛出异常:
所以使用这个:
double b;
if(Double.TryParse(elem, out d))
{
// value is a double
}
而不是
double b = Convert.ToDouble(elem);