Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on Console.ReadLine() in C#

Tags:

c#

console

    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".

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.

How can I fix it?


2 Answers

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.

like image 183
DevelopingChris Avatar answered Nov 23 '25 23:11

DevelopingChris


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). This enables the user to prevent further keyboard input when the ReadLine method is called in a loop.

So you can indeed get a null reference back from calling ReadLine(). The String.IsNullOrEmpty method will check both cases for you though.

like image 20
Ed S. Avatar answered Nov 24 '25 01:11

Ed S.