简体   繁体   English

如何从 C# 中的输入 Console.ReadLine() 获取两个 integer 值?

[英]How do I get two integer values from an input, Console.ReadLine(), in C#?

class Program
    {
        static void Main(string[] args)
        {
            var information= Console.ReadLine();
            var one= Int32.Parse(informatie.Split(' ')[0]);
            var two = Int32.Parse(informatie.Split(' ')[1]);
        }
    }

I want the user to type in two numbers, seperated by a whitespace, for example: 5 2. I want to capture the first number (5) in var one and the second number (2) in var two.我希望用户输入两个数字,用空格分隔,例如:5 2。我想捕获 var one 中的第一个数字 (5) 和 var 2 中的第二个数字 (2)。 The problem, however, is that my code doesn't work if the user, for example, types in two-digit numbers such as: 25 10. How can I make it work that my two variables one and two capture the numbers regardless of length?然而,问题是,如果用户输入两位数,例如:25 10,我的代码将不起作用。我如何才能让我的两个变量 1 和 2 捕获数字而不管长度? So another example, if a user types in: 348 3910 I want var one = 348 and var two = 3910. Another one: 2 4, var one = 2 and var two = 4.再举一个例子,如果用户输入:348 3910,我想要 var one = 348 和 var two = 3910。另一个:2 4,var one = 2 和 var two = 4。

You need to first split the string and then select the value from the array you want to use.您需要先拆分字符串,然后 select 您要使用的数组中的值。 You do not need to perform the split operation each time;不需要每次都进行拆分操作; you only need to do it once.你只需要做一次。 See the below code sample.请参阅下面的代码示例。 You can also see it in this fiddle .你也可以在这个fiddle中看到它。

var textSample = "320 520";

var textSplit = textSample.Split(' ');

Console.WriteLine(Int32.Parse(textSplit[0]));
Console.WriteLine(Int32.Parse(textSplit[1]));

Your code would look like this你的代码看起来像这样

var information= Console.ReadLine();
var textSplit = informatie.Split(' ')
var one= Int32.Parse(textSplit[0]);
var two = Int32.Parse(textSplit[1]);

I tried this one:我试过这个:

class Program
{
    static void Main(string[] args)
    {

        var information = Console.ReadLine();
        var one = Int32.Parse(information.Split(' ')[0]);
        var two = Int32.Parse(information.Split(' ')[1]);

        Console.WriteLine($" one is {one}");
        Console.WriteLine($" two is {two}");
        Console.ReadKey();
    }
}

and it works它有效

This is the console: (Click here to see image...)这是控制台:(单击此处查看图像...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM