Home > Blockchain >  How to make multiline input in C#?
How to make multiline input in C#?

Time:09-22

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 ?

CodePudding user response:

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

CodePudding user response:

Try to initialize a new variable to indicate the number of lines to enter. Then, in a loop, enter the specified number of new lines. If you do not know when the end of the input data will be, then you can complete the input with String.IsNullOrWhiteSpace, which checks whether the last line you entered is empty and this completes the input. Example:

string line;
while(!String.IsNullOrWhiteSpace(line=Console.ReadLine())) {}
  • Related