Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console : Check for Keypress (Esc)

Tags:

c#

Before you flag this, I've tried several solutions found here (I swear it is not duplicate) and end up with errors causing VS to crash.

EDIT: Some people said my loop doesn't work. The issue is not there, it has to do with the keypress enter image description here

Here is my original code :

        while (true)
            {
                Console.WriteLine("Voer een getal in : ");
                string invoer = Console.ReadLine();
                Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                string macht = Console.ReadLine();

                int getal = Convert.ToInt32(invoer);
                int getalmacht = Convert.ToInt32(macht);

                int uitkomst = (int)Math.Pow(getal, getalmacht);
                Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                Console.ReadLine();


            }

It worked fine but it did not look for keypresses.

Here is one that checks for keypress and does not throw a error :

namespace Democonsole
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Press ESC to stop.");

        do
        {
            while (!Console.KeyAvailable)
            {

                Console.WriteLine("Voer een getal in : ");
                string invoer = Console.ReadLine();
                Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                string macht = Console.ReadLine();

                int getal = Convert.ToInt32(invoer);
                int getalmacht = Convert.ToInt32(macht);

                int uitkomst = (int)Math.Pow(getal, getalmacht);
                Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                Console.ReadLine();


            }
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);




    }
}

}

It does however upon running crash and give the error as seen in the printscreen.

Any other way to do this?

EDIT : Added more examples of solutions I tried due to request.

    static void Main(string[] args)
{
    var myWorker = new MyWorker();
    myWorker.DoStuff();
    Console.WriteLine("Press any key to stop...");
    Console.ReadKey();
}

break

     while (true)
                    {
                        Console.WriteLine("Voer een getal in : ");
                        string invoer = Console.ReadLine();
                        Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                        string macht = Console.ReadLine();

                        int getal = Convert.ToInt32(invoer);
                        int getalmacht = Convert.ToInt32(macht);

                        int uitkomst = (int)Math.Pow(getal, getalmacht);
                        Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                        Console.ReadLine();
                        Console.Keypress()



`
like image 920
Maartenw Avatar asked Feb 15 '26 11:02

Maartenw


1 Answers

The error message tells you pretty much all you need to know about the error, which is that you are trying to convert a string to an integer and the string cannot be converted to an integer. Probably because it's empty.

That's only part of the problem though, which I will address later.

First, your loop structure is wrong. The inner loop runs as long as there is no keypress waiting to be read. But right at the end of the loop's body you are expressly clearing the content of the console buffer, so it will never exit the inner loop.

Consider this minimal example:

while (!Console.KeyAvailable)
{
    Console.ReadLine();
}

Assuming that there are no keys waiting to be read when it encounters the while statement (which will skip the whole thing) the inner statement will accumulate characters from keystrokes until you press enter then return the characters as a string. A few microseconds later it will check to see if you have pressed another key after the enter, which is quite literally impossible. As a result this is a strange way of writing an infinite loop.

Next problem is that you ask for input from the user and assume that the input is going to be valid. It's not, which is what is causing those exceptions you got earlier. Always assume that the user is going to enter something that your program is not expecting and figure out how to deal with it going wrong.

For instance:

string invoer = Console.ReadLine();
int getal;
if (!int.TryParse(invoer, out getal))
{
    Console.WriteLine("Invalid value '{0}'", invoer);
    continue;
}

If the value doesn't convert to a number then this will complain about it and go back to the start of the loop. You might also want to try exiting the loop if the value is empty:

string invoer = Console.ReadLine();
if (string.IsNullOrEmpty(invoer))
    break;
int getal;
if (!int.TryParse(invoer, out getal))
{
    Console.WriteLine("Invalid value '{0}'", invoer);
    continue;
}

That at least gives you a way out of the loop, which you don't have at the moment.

like image 80
Corey Avatar answered Feb 18 '26 01:02

Corey