mike
mike

Reputation: 172

How to exit a console application without requiring enter

What would be the best way to exit an application when a user types x without having to hit enter. The current code I am using is this:

Console.WriteLine("\nType x to exit > ");
string test = Console.ReadLine();
while (test != "x")
{
    Console.WriteLine("\nType x to exit > ");
    test = Console.ReadLine();
}

This will make the user experience better.

Upvotes: 2

Views: 4165

Answers (3)

Matt Varblow
Matt Varblow

Reputation: 7881

You could do something like this:

do
{
    Console.WriteLine("\nType x to exit > ");
}
while (Console.ReadKey().KeyChar != 'x');

Upvotes: 0

user1454661
user1454661

Reputation:

Console.ReadKey() let you read a single key press. Console.readLine() is waiting for a line termination. Here's the doc for reference:

http://msdn.microsoft.com/en-us/library/471w8d85.aspx

You can read the first character and then if it's not "x", read a line input (and prepend the first char received before).

Upvotes: 1

Eric J.
Eric J.

Reputation: 150108

You can use Console.ReadKey instead.

Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window.

Upvotes: 3

Related Questions