C++ C# 中的输入链接

发布于 2024-08-24 07:48:34 字数 456 浏览 4 评论 0原文

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

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

您只需输入 3 5 并按 Enter 键,这些值就可以了。 然而,在 C# 中,我必须将它分开(据我所知),如下所示:

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

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

I am trying to learn C# coming from C++. I am writing just some basic console stuff to get a feel for it and was wondering if it is possible to do simple chaining of inputs in C#. For example in C++:

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

You could then just input 3 5 and hit enter and the values will be fine.
In C# however I have to split it up(as far as I can tell) like this:

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

Maybe I am just missing something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

聊慰 2024-08-31 07:48:34

您可以使用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]);

you can read the entire line with Console.ReadLine and can get the two variables in a variety of ways split, basic test parsing, or Regex.


A short Ex

  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]);
浪推晚风 2024-08-31 07:48:34

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

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

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

留给读者作为练习。

There's nothing that prevents input chaining from working in C#, you just won't get the nice operator syntax because C# lets you redefine fewer operators.

Writing an extension method to let you do:

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

is left as an exercise for the reader.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文