Mikey D
Mikey D

Reputation: 73

Separating user input numbers in C#

How can I separate a set of numbers in a console app in C# instead of asking the user for each individual number? E.g. instead of doing this...

        double first, second, third, fourth;

        Console.Write("Please enter first digit: ");
        first = Convert.ToDouble(Console.ReadLine());
        Console.Write("Please enter second digit: ");
        second = Convert.ToDouble(Console.ReadLine());
        Console.Write("Please enter third digit: ");
        third = Convert.ToDouble(Console.ReadLine());
        Console.Write("Please enter fourth digit: ");
        fourth = Convert.ToDouble(Console.ReadLine());

Upvotes: 0

Views: 7067

Answers (3)

PinnyM
PinnyM

Reputation: 35533

You can have them enter all digits at once with a separator of some sort (space in this example).

Console.Write("Please enter a bunch of digits separated by a space: ");
var allDigits = Console.ReadLine().Split(' ');
Double[] digits = allDigits.Select(d => Covert.ToDouble(d)).ToArray();

If your requirement is limited to 4 inputs restrict the allDigit by using IEnumerable<string>.Take(4)

Console.Write("Please enter a bunch of digits separated by a space: ");
var allDigits = Console.ReadLine().Split(' ').Take(4);
Double[] digits = allDigits.Select(d => Covert.ToDouble(d)).ToArray();

Upvotes: 5

lc.
lc.

Reputation: 116448

Here's one way:

Console.Write("Please enter numbers, comma-separated: ");
var numbers = Console.ReadLine()
    .Split(',')
    .Select(x => Double.Parse(x.Trim()))
    .ToList();

In real-life code though it would probably be better to use TryParse and throw an error back to the user.

Upvotes: 1

Parimal Raj
Parimal Raj

Reputation: 20565

Make use of array, it can help you to faster read/write operation into variables

    double[] numbers = new double[4];

    for (int i = 0; i < 4; i++)
    {
        Console.WriteLine("Enter {0} of 4 Number : ", i + 1);
        numbers[i] = Convert.ToDouble(Console.ReadLine());
    }

    // numbers[0] = first
    // numbers[1] = second
    // numbers[2] = third
    // numbers[3] = fourth

If you really want to use four variables then, this can be the most short way :

    double first, second, third, fourth;

    for (int i = 1; i <= 4; i++)
    {
        Console.WriteLine("Enter a number : ");
        double input = Convert.ToDouble(Console.ReadLine());
        switch (i)
        {

            case 1:
                first = input;
                break;

            case 2:
                second = input;
                break;

            case 3:
                third = input;
                break;
            case 4:
                fourth = input;
                break;

        }
    }

Upvotes: 2

Related Questions