使用C#在一行中读取两个整数

Nad*_*em 29 c# console parsing integer

我知道如何使控制台读取两个整数,但每个整数由它自己像这样

int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

如果我输入两个数字,即(1 2),值(1 2),不能解析整数我想要的是如果我输入1 2那么它将把它作为两个整数

Ani*_*Ani 27

一种选择是接受单行输入作为字符串然后处理它.例如:

//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]);
Run Code Online (Sandbox Code Playgroud)

这种方法的一个问题是,如果用户没有以预期格式输入文本,它将失败(通过抛出IndexOutOfRangeException/ FormatException).如果可以,您将必须验证输入.

例如,使用正则表达式:

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
}
Run Code Online (Sandbox Code Playgroud)

或者:

  1. 确认输入分成正好 2串.
  2. 使用int.TryParse试图对字符串解析成数.


Fra*_*ank 6

你需要类似的东西(没有错误检查代码)

var ints = Console
            .ReadLine()
            .Split()
            .Select(int.Parse);
Run Code Online (Sandbox Code Playgroud)

这会读取一行,在空格上拆分并将拆分字符串解析为整数.当然,实际上你需要检查输入的字符串是否实际上是有效整数(int.TryParse).


Rvd*_*vdK 5

然后,您应该首先将其存储在字符串中,然后使用空格作为标记将其拆分.