简体   繁体   English

是否可以从C#的控制台读取未知数量的行?

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

有一个函数可以从控制台输入中读取一行( Console.ReadLine() ),但是我希望读取一行或任意数量的行,这在编译时是未知的。

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). 只需一次在for循环(如果您知道在开始阅读时需要多少行)或在while循环(如果您想要)中一次读取一行(使用ReadLine()或您需要的其他任何内容)在达到EOF或特定输入时停止读取)。

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". 此处的其他一些答案会一直循环直到遇到空行,而其他答案则希望用户键入一些特殊内容,例如“ 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. 对于重定向的输入,当Console.ReadLine()到达文件末尾时,它将返回null。 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). 如果用户以交互方式运行程序,则他们必须知道如何输入文件字符的结尾(Ctrl + Z后按Enter或F6后按Enter)。 If it is an interactive user you might need to let them know how to signal the end of input. 如果是交互式用户,则可能需要让他们知道如何用信号通知输入结束。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM