在C#中分离用户输入数字

时间:2013-02-22 04:05:52

标签: c# console-application

如何在C#中的控制台应用中分隔一组数字,而不是向用户询问每个号码?例如。而不是这样做......

        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());

3 个答案:

答案 0 :(得分:5)

您可以使用某种分隔符(本例中为空格)一次输入所有数字。

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();

如果您的要求仅限4 inputs使用allDigit限制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();

答案 1 :(得分:2)

利用array,它可以帮助您更快地读/写操作变量

    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

如果你真的想要使用四个变量,那么这可能是最简短的方法:

    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;

        }
    }

答案 2 :(得分:1)

这是一种方式:

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

在现实代码中,尽管使用TryParse并向用户抛出错误可能会更好。