[英]Question on Console.ReadLine() in C#
static void Main()
{
string str;
str = Console.ReadLine();
while (str != null)//HERE!
{
str = str.Remove(0, 1);
str = str.Remove(str.Length - 1, 1);
string[] value = str.Split(',');
int[] intval = new int[value.Length];
for (int i = 0; i < value.Length; ++i)
{
bool re = int.TryParse(value[i], out intval[i]);
Console.WriteLine(intval[i]);
}
str = Console.ReadLine();
}
}
嗨,在上面的程序中,我想判斷控制台中是否有使用“str!= null”讀取的內容。
但是,ReadLine()向我返回一個“”而不是null,程序可以進入while循環並生成錯誤的結果。
我該如何解決?
while(!string.IsNullOrEmpty(str))
使用內置方法檢查它們
如果它回來是空的,他們只需按下進入,你就可以使用它作為你的哨兵,所以你可以失敗。
來自文檔:
如果在方法從控制台讀取輸入時按下CTRL + Z字符,則該方法返回空引用(在Visual Basic中為Nothing)。 這使得用戶可以在循環中調用ReadLine方法時阻止進一步的鍵盤輸入。
所以你確實可以從調用ReadLine()獲得一個null引用。 String.IsNullOrEmpty方法將為您檢查兩種情況。
ReadLine阻塞,直到用戶按下回車鍵。 所以如果你只按Enter鍵,你就會得到一個空字符串。
while (!string.IsNullOrEmpty(str))
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.