【问题标题】:C++ input chaining in C#C# 中的 C++ 输入链接
【发布时间】:2010-03-09 00:31:24
【问题描述】:

我正在尝试从 C++ 学习 C#。我正在编写一些基本的控制台内容来感受它,并且想知道是否可以在 C# 中进行简单的输入链接。例如在 C++ 中:

cout<<"Enter two numbers: ";
cin >> int1 >> int2;

然后您可以输入 3 5 并按回车键,这些值就可以了。 然而,在 C# 中,我必须像这样拆分它(据我所知):

Console.Write("Enter the first number: ";
int1 = (char)Console.Read();
Console.Writeline("");
Console.Write("Enter the second number: ";
int2 = (char)Console.Read();

也许我只是错过了一些东西。

【问题讨论】:

    标签: c# input chaining chain


    【解决方案1】:

    您可以使用Console.ReadLine 阅读整行,并且可以通过拆分、基本测试解析或正则表达式的多种方式获取这两个变量。


    一个简短的前任

      Console.WriteLine("Enter two Numbers");
      int Num1 = 0 ,Num2 = 0 ;
      Match M = Regex.Match(Console.ReadLine(),@"(\d+) (\d+)");
      Num1 = int.Parse(M.Groups[1].Value);
      Num2 = int.Parse(M.Groups[2].Value);
    
      //Using Split 
      Console.WriteLine("Enter two Numbers");
      string[] Ints = (Console.ReadLine().Split(' '));
      Num1 = int.Parse(Ints[0]);
      Num2 = int.Parse(Ints[1]);
    

    【讨论】:

      【解决方案2】:

      没有什么可以阻止输入链在 C# 中工作,你只是不会得到好的运算符语法,因为 C# 允许你重新定义更少的运算符。

      编写一个扩展方法让你这样做:

      Console.In.Read(out int1).Read(out int2);
      

      留给读者作为练习。

      【讨论】:

        猜你喜欢
        • 2011-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 2014-02-03
        • 1970-01-01
        相关资源
        最近更新 更多