简体   繁体   English

关于C#中Console.ReadLine()的问题

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

Hi, in the program above, I want to judge whether there is stuff not read in the console using "str!=null". 嗨,在上面的程序中,我想判断控制台中是否有使用“str!= null”读取的内容。

However,the ReadLine() returned a "" to me instead of a null, and the program can get into the while loop and generate a wrong result. 但是,ReadLine()向我返回一个“”而不是null,程序可以进入while循环并生成错误的结果。

How can I fix it? 我该如何解决?

while(!string.IsNullOrEmpty(str))

check it for both with the built in method 使用内置方法检查它们

if it comes back empty they just pressed enter, and you've it your sentinel either way, so you can fail on that. 如果它回来是空的,他们只需按下进入,你就可以使用它作为你的哨兵,所以你可以失败。

From the docs: 来自文档:

If the CTRL+Z character is pressed when the method is reading input from the console, the method returns a null reference (Nothing in Visual Basic). 如果在方法从控制台读取输入时按下CTRL + Z字符,则该方法返回空引用(在Visual Basic中为Nothing)。 This enables the user to prevent further keyboard input when the ReadLine method is called in a loop. 这使得用户可以在循环中调用ReadLine方法时阻止进一步的键盘输入。

So you can indeed get a null reference back from calling ReadLine(). 所以你确实可以从调用ReadLine()获得一个null引用。 The String.IsNullOrEmpty method will check both cases for you though. String.IsNullOrEmpty方法将为您检查两种情况。

ReadLine blocks till the user presses enter. ReadLine阻塞,直到用户按下回车键。 So if you just press enter, you'd get a empty string. 所以如果你只按Enter键,你就会得到一个空字符串。

 while (!string.IsNullOrEmpty(str))
{
...
}

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

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