tags:

views:

409

answers:

4
    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?

A: 

ReadLine blocks till the user presses enter. So if you just press enter, you'd get a empty string.

Gishu
+5  A: 
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.

DevelopingChris
A: 
 while (!string.IsNullOrEmpty(str))
{
...
}
ArsenMkrt
+1  A: 

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.

Ed Swangren