0

I'm having problems with my console input. Code is:

using System;
using System.Linq;

class Training
{
    static void Main()
   {
       double[] arr = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();
       int[] roundedNums = new int[arr.Length];
       for (int i = 0; i < arr.Length; i++)
       {
           roundedNums[i] = (int)Math.Round(arr[i], MidpointRounding.AwayFromZero);
       }
       for (int i = 0; i < roundedNums.Length; i++)
       {
           Console.WriteLine("{0} => {1}", arr[i], roundedNums[i]);
       }
   }
}

When i start the program i get an exception if i use . instead of , (example: if I type 3.5 i get an error, but if I type 3,5 the program works fine). I'm using Visual Studio Community 2015.

How can i solve this?

2
  • 1
    what exception do you get? Commented Oct 9, 2016 at 9:16
  • 2
    You're running in a Culture different to English. Some culutres only ',' char as a decimal separator. Commented Oct 9, 2016 at 9:17

2 Answers 2

1

You can change your code to use specific culture. For example invariant culture, which would then treat '.' as a decimal separator and ',' as group separator.

You can apply InvariantCulture as such:

double[] arr = Console.ReadLine()
               .Split(' ')
               .Select(x => double.Parse(x, CultureInfo.InvariantCulture))
               .ToArray();

Some of the cultures default a space (' ') as decimal or group separators and '.' or ',' is interpreted as invalid input.

You can look up your separators used by default with two properties:

Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator;
Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
Sign up to request clarification or add additional context in comments.

1 Comment

@ognyan Type Region in start search > Advanced settings... and you can choose what separators to use for your default culture. You can also use properties mentioned in the answer to override your current threads culture settings. For example: Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator = ",";
0

replace this :

double[] arr = Console.ReadLine().Split('.').Select(double.Parse).ToArray();

with your this line :

double[] arr = Console.ReadLine().Split(' ').Select(double.Parse).ToArray();

Is it working ? let me know. :)

2 Comments

This is really wrong :-) The split stand for to let user to enter multiple values not for spliting a single value
@CodeNotFound okey sir. then i misunderstood his Question . my apology

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.