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

三世轮回 提交于 2021-02-08 13:28:10

问题


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.


回答1:


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
}



回答2:


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.




回答3:


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;
}
}



回答4:


The best thing to do here is use a loop:

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 could 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");


来源:https://stackoverflow.com/questions/8707100/is-it-possible-to-read-unknown-number-of-lines-from-console-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!