简体   繁体   中英

C# Console.Readkey - wait for specific input

I have a small C# console app I am writing.

I would like the app to wait for instruction from the user regarding either a Y or a N keypress (if any other key is pressed the app ignores this and waits for either a Y or a N and then runs code dependent on the Y or N answer.

I came up with this idea,

while (true)
{
    ConsoleKeyInfo result = Console.ReadKey();
    if ((result.KeyChar == "Y") || (result.KeyChar == "y"))
    {
         Console.WriteLine("I'll now do stuff.");
         break;
    }
    else if ((result.KeyChar == "N") || (result.KeyChar == "n"))
    {
        Console.WriteLine("I wont do anything");
        break;
    }
}

Sadly though VS says its doesnt like the result.Keychat == as the operand cant be applied to a 'char' or 'string'

Any help please?

Thanks in advance.

KeyChar is a char while "Y" is a string .

You want something like KeyChar == 'Y' instead.

Check this instead

string result = Console.ReadLine();

And after check the result

What your looking for is something like this

       void PlayAgain()
    {
        Console.WriteLine("Would you like to play again? Y/N: ");
        string result = Console.ReadLine();
        if (result.Equals("y", StringComparison.OrdinalIgnoreCase) || result.Equals("yes", StringComparison.OrdinalIgnoreCase))
        {
            Start();
        }
        else
        {
            Console.WriteLine("Thank you for playing.");
            Console.ReadKey();
        }
    }

You probably want the user to confirm their response by pressing enter, so ReadLine is best. Also convert the string response to upper case for generic comparison check. Like so:

string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
    // Do what ya do ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM