Search code examples
c#.netconsole

How to make multiline input in C#?


I'm intrested in C++ code like this:

 while(getline(cin, n)) 

but I want to do this in C# and I don't know how to do something like this. I have 10 line input, which needs to be in one string, but with Console.ReadLine() it only saves me one line out of 10 to string. My string variable has to have 10 line text,

For example:

"first line of text\nsecond line\nthird". 

Is it any way to do something like this, like in C++?


Solution

  • If you want to mimic getline(cin, n), you can try reading from stdin, i.e.

    using System.IO;
    
    ... 
    
    // Read line by line from stdin
    public static IEnumerable<string> ReadStdInLines() {
      using var reader = new StreamReader(Console.OpenStandardInput());
    
      for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        yield return line;
    }
    

    For instance:

    using System.Linq;
    
    ...
    
    string[] lines = ReadStdInLines()
      .Take(10) // at most 10 lines
      .ToArray();