Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to read unknown number of lines from console in C#?

Tags:

c#

console

There is a function, which can read a single line from the console input (Console.ReadLine()), but I wish to read or some arbitrary number of lines, which is unknown at compile time.

like image 397
nenito Avatar asked Jan 03 '12 01:01

nenito


2 Answers

Of course it is. Just use just read a single line (using ReadLine() or whatever else you please) at a time within either a for loop (if you know at the beginning of reading how many lines you need) or within a while loop (if you want to stop reading when you reach EOF or a certain input).

EDIT:

Sure:

while ((line = Console.ReadLine()) != null) {
    // Do whatever you want here with line
}
like image 85
Dan Avatar answered Oct 21 '22 05:10

Dan


Some of the other answers here loop until a null line is encountered while others expect the user to type something special like "EXIT". Keep in mind that reading from the console could be either a person typing or a redirected input file:

myprog.exe < somefile.txt

In the case of redirected input Console.ReadLine() would return null when it hits the end of the file. In the case of a user running the program interactively they'd have to know to how to enter the end of file character (Ctrl+Z followed by enter or F6 followed by enter). If it is an interactive user you might need to let them know how to signal the end of input.

like image 32
Mike W Avatar answered Oct 21 '22 04:10

Mike W