Vesk
Vesk

Reputation: 125

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

I have just started learning 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++. The input a b c should be able to be read as:

a b c

or

a b
c

or

a
b c

or

a
b
c

and the result should be the same.

Upvotes: 3

Views: 4528

Answers (1)

Eoin Campbell
Eoin Campbell

Reputation: 44268

The Console class supports two read methods.

Read() will read a single character ReadLine() will read all content to the end of the line (e.g. until an Environment.NewLine character.

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.

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();
}

enter image description here

Upvotes: 9

Related Questions