![](/img/trans.png)
[英]Read text from file (c#) of unknown number of lines and add lines to predefined labels
[英]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.