使用 C# 在一行中读取两个整数 [英] reading two integers in one line using C#

查看:43
本文介绍了使用 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.

例如,使用正则表达式:

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
}

或者:

  1. 验证输入是否分成恰好 2 个字符串.
  2. 使用int.TryParse尝试将字符串解析为数字.
  1. Verify that the input splits into exactly 2 strings.
  2. Use int.TryParse to attempt to parse the strings into numbers.

这篇关于使用 C# 在一行中读取两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆