繁体   English   中英

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

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

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

当然是这样。 只需一次在for循环(如果您知道在开始阅读时需要多少行)或在while循环(如果您想要)中一次读取一行(使用ReadLine()或您需要的其他任何内容)在达到EOF或特定输入时停止读取)。

编辑:

当然:

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

此处的其他一些答案会一直循环直到遇到空行,而其他答案则希望用户键入一些特殊内容,例如“ EXIT”。 请记住,从控制台读取的内容可能是输入的人,也可能是重定向的输入文件:

myprog.exe < somefile.txt

对于重定向的输入,当Console.ReadLine()到达文件末尾时,它将返回null。 如果用户以交互方式运行程序,则他们必须知道如何输入文件字符的结尾(Ctrl + Z后按Enter或F6后按Enter)。 如果是交互式用户,则可能需要让他们知道如何用信号通知输入结束。

最好的方法是使用循环:

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

或者,您可以执行以下操作:

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

简单的例子:

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