Here’s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.
Here’s a simple hack to do this :
private static void FlushKeyboard()
{
while (Console.In.Peek() != -1)
Console.In.Read();
}
Now you can use it as follows :
char x = (char)Console.Read();
FlushKeyboard();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);
Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.
It is really useful for resolving
System.FormatException :
“Input string was not in a correct format.”
where we try to repeatedly excute code like
——————————————————-
Console.WriteLine(“Please press enter key”);
Console.Read();
intA = int.Parse(Console.ReadLine());
intB = int.Parse(Console.ReadLine());
Thank you, for this solution.
I was looking for something like that, the only thing i changed was Console.In.Read() for this Console.In.ReadLine() becouse I needed for readline and worked like a charm!
Grettings from Mexico!