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

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

+5
source share
4 answers

Of course. Just use only one line (using ReadLine()or something else that you like) at the same time in a for loop (if you know at the beginning of reading how many lines you need) or inside a while loop (if you want to stop reading when you reach EOFor specific input).

EDIT:

Of course:

while ((line = Console.ReadLine()) != null) {
    // Do whatever you want here with line
}
+12
source

, , , - , "EXIT". , , :

myprog.exe < somefile.txt

Console.ReadLine() null, . , , , (Ctrl + Z, F6, ). , , .

+2

It is best to use a loop here:

string input;

Console.WriteLine("Input your text (type EXIT to terminate): ");
input = Console.ReadLine();

while (input.ToUpper() != "EXIT")
{
    // do something with input

    Console.WriteLine("Input your text(type EXIT to terminate): ");
    input = Console.ReadLine();
}

Or you can do something like this:

string input;

do
{
    Console.WriteLine("Input your text (type EXIT to terminate): ");
    input = Console.ReadLine();

    if (input.ToUpper() != "EXIT")
    {
        // do something with the input
    }
} while (input.ToUpper() != "EXIT");
+1
source

simple example:

class Program
{
static void Main()
{
CountLinesInFile("test.txt"); // sample input in file format
}

static long CountLinesInFile(string f)
{
long count = 0;
using (StreamReader r = new StreamReader(f))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {
    count++;
    }
}
return count;
}
}
+1
source

All Articles