user53670
user53670

Reputation:

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

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?

Upvotes: 3

Views: 4674

Answers (4)

Ed Swangren
Ed Swangren

Reputation: 124622

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.

Upvotes: 2

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

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

Upvotes: 0

DevelopingChris
DevelopingChris

Reputation: 40788

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.

Upvotes: 8

Gishu
Gishu

Reputation: 136593

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

Upvotes: 0

Related Questions