使用C#读取两个整数一行 [英] reading two integers in one line using C#
问题描述
我知道如何使一个控制台读取两个整数,但每个整数它的自我是这样
i know how to make a console read two integers but each integer by it self like this
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
如果我进入两个数字,即(1 2),值(1 2),不能被解析为整数
我想要的是,如果我进入1 2那么它将把它作为两个整数
if i entered two numbers, i.e (1 2), the value (1 2), cant be parse to integers what i want is if i entered 1 2 then it will take it as two integers
推荐答案
一个选择是接受输入的一行作为一个字符串,然后对其进行处理。
例如:
One option would be to accept a single line of input as a string and then process it. For example:
//Read line, and split it by whitespace into an array of strings
string[] tokens = Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(tokens[0]);
//Parse element 1
int b = int.Parse(tokens[1]);
这种方法的一个问题是,它会失败(抛出一个 IndexOutOfRangeException
/ FormatException
)如果用户没有进入预期的格式文本。如果这是可能的,你将不得不验证输入。
One issue with this approach is that it will fail (by throwing an IndexOutOfRangeException
/ FormatException
) if the user does not enter the text in the expected format. If this is possible, you will have to validate the input.
例如,与常规的前pressions:
For example, with regular expressions:
string line = Console.ReadLine();
// If the line consists of a sequence of digits, followed by whitespaces,
// followed by another sequence of digits (doesn't handle overflows)
if(new Regex(@"^\d+\s+\d+$").IsMatch(line))
{
... // Valid: process input
}
else
{
... // Invalid input
}
或者
- 验证输入分成的究竟的2串。
- 使用
int.TryParse
来的尝试的解析字符串转换为数字。
- Verify that the input splits into exactly 2 strings.
- Use
int.TryParse
to attempt to parse the strings into numbers.
这篇关于使用C#读取两个整数一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!