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.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With