user11064779
user11064779

Reputation: 23

Need to enter escape key to end program

I am writing a simple calculator where the user can perform operations and end the program by entering -1.

How can I modify how I take input from the user so that they can use the escape key instead of entering -1?

using System;

namespace A_4
{
    class Calculator
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("\tSimple Calculator");

            while (true) 
            {
                Console.WriteLine("********************************");                
                Console.Write("Enter First Number: ");
                double operand1 = Convert.ToDouble(Console.ReadLine());

                if (operand1 == -1)
                {
                    break;
                }

                Console.Write("\nEnter Second Number: ");
                double operand2 = Convert.ToDouble(Console.ReadLine());
                if (operand2 == -1)
                {
                    break;
                }

                Console.Write("\nEnter operator +, -, *, /): ");

                // ... operate on the entered input
        }
    }
}

Upvotes: 2

Views: 365

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

Since you want to get a specific key, you'll not be able to use Console.ReadLine, you have to read each character to be able to determine if ESC was pressed.

The best would be to create a helper method to get user input:

public static double GetUserInput()
{
    string numbersEntered = "";
    ConsoleKeyInfo lastKey;

    // read keys until Enter is pressed
    while ((lastKey = Console.ReadKey()).Key != ConsoleKey.Enter)
    {
        // if Escape is pressed, exit
        if (lastKey.Key == ConsoleKey.Escape)
        {
            return -1;
        }

        // otherwise, add the key entered to the input
        numbersEntered += lastKey.KeyChar.ToString();
    }

    // and convert the final number to double
    return Convert.ToDouble(numbersEntered);
}

With that, you can just do double operand1 = GetUserInput(); and you know that if it's -1 (as an example), you have to exit.

Upvotes: 2

Related Questions