first Console.ReadLine() returns immediately

荒凉一梦 提交于 2020-06-23 14:17:50

问题


I am writing a really silly program.

I have no idea why the following code won't work:

static void Main(string[] args){
        <Some silly code>
        Console.WriteLine("Please choose the lab you are working on:");
        int choose = Console.Read();
        <Some more silly code, including 1 Console.writeLine() call >

        Console.WriteLine("Enter the DB server location");
        string DBServer = Console.ReadLine();
        Console.WriteLine("Enter the DB name");
        string DBName = Console.ReadLine();
    }

When I run the program, it never waits for the first ReadLine statement

string DBServer = Console.ReadLine();

It prints the two rows immediately

Enter the DB server location  
Enter the DB name

And then reads the second ReadLine string DBName = Console.ReadLine();

When I check the input form user, it indeed reads the second one well, but the first string comes out empty.
Any ideas?


回答1:


This is because you are using Console.Read which will reach a character but will leave the carriage-return after it alone. Which will then be picked up by ReadLine.

Input is a stream. When you are entering a single character and then hit return there are 2–3 characters in the stream (depending on the system): The character you entered and the line break. Read just gives you the next character in the stream, while ReadLine will read everything up to the next line break. Again, from the stream. So your Read fetches a character and ReadLine already finds the next line break and thus continues happily.

You can either insert a dummy ReadLine, or use ReadKey which will just read a key and won't need a return before your program sees the input, or use ReadLine for the single-character input as well.



来源:https://stackoverflow.com/questions/17167132/first-console-readline-returns-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!