Franva
Franva

Reputation: 7077

Console.ReadLine() skips the first input character

Console.WriteLine("You have not installed Microsoft SQL Server 2008 R2, do you want to install it now? (Y/N): ");
//var answerKey = Console.ReadKey();
//var answer = answerKey.Key;
var answer = Console.ReadLine();
Console.WriteLine("After key pressed.");
Console.WriteLine("Before checking the pressed key.");

//if(answer == ConsoleKey.N || answer != ConsoleKey.Y)
if (string.IsNullOrEmpty(answer) || string.IsNullOrEmpty(answer.Trim()) || string.Compare(answer.Trim(), "N", true) == 0)
{
    Console.WriteLine("The installation can not proceed.");
    Console.Read();
    return;
}

I have tried to input these:

I have checked other similar posts, but none of them solves my problem. The ReadLine() still skips the 1st input character.

UPDATE Solved, see below.

Upvotes: 2

Views: 3945

Answers (3)

Franva
Franva

Reputation: 7077

Thank you all for replying my post.

It's my bad that not taking consideration of the multi-thread feature in my code. I will try to explain where I was wrong in order to say thank you to all your replies.

BackgroundWorker worker = .....;
  public static void Main(string[] args)
    {
        InitWorker();
        Console.Read();
    }

public static void InitWorker()
{
    ....
    worker.RunWorkerAsync();
}


static void worker_DoWork(....)
{
  .....this is where I wrote the code...
}

The problem was I started a sub-thread which runs asynchronously with the host thread. When the sub-thread ran to this line : var answer = Console.ReadLine(); the host thread ran to the Console.Read(); at the same time. So what happened was it looked like I was inputting a character for var answer = Console.ReadLine();, but it actually fed to the Console.Read() which was running on the host thread and then it's the turn for the sub-thread to ReadLine(). When the sub-thread got the input from keyboard, the 1st inputted character had already been taken by the host thread and then the whole program finished and closed.

I hope my explanation is clear.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121649

Suggested change:

Console.Write("Enter some text: ");
String response = Console.ReadLine();
Console.WriteLine("You entered: " + response + ".");

Key points:

1) A string is probably the easiest type of console input to handle

2) Console input is line oriented - you must type "Enter" before the input becomes available to the program.

Upvotes: 1

Driftware
Driftware

Reputation: 99

Basically you need to change Console.Read --> Console.ReadLine

Upvotes: 0

Related Questions