简体   繁体   English

如何读取控制台输入,直到空格或在C#中输入

[英]How to read console input until space or enter in C#

I have just started learning C#. 我刚刚开始学习C#。 When it comes to reading input from the console I know there is Console.ReadLine() which reads input until the end of the line, but I am looking to read input until either the end of the line or a space, somewhat like std::cin in c++. 当涉及到从控制台读取输入时,我知道有Console.ReadLine()它将读取输入直到行尾,但是我希望读取输入直到行尾或空格,有点像std::cin在C ++中。 The input abc should be able to be read as: 输入abc应该可以读取为:

a b c

or 要么

a b
c

or 要么

a
b c

or 要么

a
b
c

and the result should be the same. 结果应该是相同的。

The Console class supports two read methods. Console类支持两种读取方法。

Read() will read a single character ReadLine() will read all content to the end of the line (eg until an Environment.NewLine character. Read()将读取单个字符ReadLine()将读取所有内容直至该行的末尾(例如,直到Environment.NewLine字符为止)。

It appears from your info above, that you simply want to read everything over multiple lines and then split it into tokens. 从上面的信息中可以看出,您只是想读取多行内容,然后将其拆分为令牌。 You can do this by grabbing the standard input stream and reading it to "the end"... that is when a CTRL + Z is received. 您可以通过获取标准输入流并将其读取到“结尾”来完成此操作,也就是收到CTRL + Z时

using (var sr = new StreamReader(Console.OpenStandardInput(), Console.InputEncoding))
{
    var input = sr.ReadToEnd();

    var tokens = input.Replace(Environment.NewLine, " ").Split(" ");

    foreach (var t in tokens)
    {
        Console.WriteLine($"Token: \"{t}\"");
    }

    Console.Read();
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM