Question about 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 above program, I want to judge if there is material that cannot be read in the console using "str! = Null".

However, ReadLine () returned me "" instead of zero, and the program may fall into the while loop and create the wrong result.

How can i fix this?

+3
source share
4 answers
while(!string.IsNullOrEmpty(str))

check it as with the built-in method

if it returns empty, they just press the enter button, and you have it your watchman anyway, so you may fail.

+8
source

From the docs:

CTRL + Z , , (Nothing Visual Basic). ReadLine .

, ReadLine(). String.IsNullOrEmpty .

+3

ReadLine blocks until the user presses the enter button. Therefore, if you just press enter, you will get an empty string.

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

Source: https://habr.com/ru/post/1711964/


All Articles