-1

class Program {
 public static void Main (string[] args) {
   
 string S1 = Console.ReadLine();
 string S2 = Console.ReadLine();

 double [] D1 = Array.ConvertAll(S1.Split(' '), Double.Parse);
 double [] D2 = Array.ConvertAll(S2.Split(' '), Double.Parse);

The final part of it isn't working, for some reason. After i enter the imput, the console says

Unhandled exception. System.FormatException: Input string was not in a correct format. at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Double.Parse(String s) at System.Array.ConvertAll[TInput,TOutput](TInput[] array, Converter`2 converter) at Program.Main(String[] args) in /home/runner/distancia-entre-dois-pontos/main.cs:line 9

Can anyone help?

  • https://stackoverflow.com/questions/9524682/fastest-way-to-convert-string-array-to-double-array – tony_merguez Dec 13 '21 at 21:14
  • 4
    Your code looks correct, but it doesn't handle bogus input. If you type "123 abc", `Double.Parse` will throw `FormatException` when trying to parse "abc". How this should be fixed depends on the behavior you desire. – jods Dec 13 '21 at 21:16

1 Answers1

0

Use some LINQ and Extension methods

static class Program
{
    static void Main(string[] args)
    {
        string text1 = "4376.0 4328.0 14.71 116.7 14.01 0.9912 46.74";
        double[] row1 = text1.ParseList();
        string text2 = "4376.0,4328.0,14.71,116.7,14.01,0.9912,46.74";
        double[] row2 = text2.ParseList(',');
    }
}

public static class Extensions
{
    public static double[] ParseList(this string text, char token = ' ')
    {
        return text.Split(token).Select((item) => ParseValue(item)).ToArray();
    }
    public static double ParseValue(this string text)
    {
        if (double.TryParse(text.Trim(), out double x))
        {
            return x;
        }
        return 0;
    }
}
John Alexiou
  • 28,472
  • 11
  • 77
  • 133