【问题标题】:How to get multiple input in one line in c# [closed]如何在c#中的一行中获取多个输入[关闭]
【发布时间】:2021-10-26 07:55:12
【问题描述】:

c#代码,我无法解决这个问题:

    int a, b = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine(a);
    Console.WriteLine(b);
   
    Console.ReadLine();

谁能帮帮我。

【问题讨论】:

  • 为什么要这样做?只需分两行即可。
  • 如果您有很多输入,请使用循环 + 数组/列表
  • 如果希望用户在一行中输入多个值,则必须手动拆分:Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x))
  • 为什么要限制在一行?

标签: c# input


【解决方案1】:

您可以使用此示例:

(int a,int  b) = (Convert.ToInt32(Console.ReadLine()),Convert.ToInt32(Console.ReadLine()));

【讨论】:

  • @PaulF 这不取决于 OP 的“一行”的含义吗?我将其解释为一行代码。尽管有点滥用ValueTuple,但哈米德的回答实现了这一点。
  • @Llama - 一个措辞不当的问题,可以解释
  • @PaulF 确实如此。
【解决方案2】:

管理到 euhm,滥用 Linq 在一行中完成。但说真的,只需使用几行代码。

(int? a, int? b) = 
Console
.ReadLine()
.Split(' ')
.Select(x => Convert.ToInt32(x))
.Aggregate(((int?)null, (int?)null), (l, next) => l.Item1 == null ? (next, (int?)null) : (l.Item1, next));

读取输入并将其拆分:

string input = Console.ReadLine();
var parts = input.Split(' ');
int a = Convert.ToInt32(parts[0]);
int b = Convert.ToInt32(parts[1]);

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2012-12-27
    • 1970-01-01
    • 2014-06-02
    • 2011-12-18
    • 2022-01-10
    相关资源
    最近更新 更多