amitfr
amitfr

Reputation: 1093

first Console.ReadLine() returns immediately

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?

Upvotes: 0

Views: 1130

Answers (1)

Joey
Joey

Reputation: 354784

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.

Upvotes: 4

Related Questions