خرید بک لینک

Vote count: 0

I have some code which exits the program when the user types 'q'

//press 'q' to quit application
ConsoleKeyInfo info = Console.ReadKey(true); ;
while (info.KeyChar != 'q') {
    info = Console.ReadKey(true);
}

How do I modify this structure so that there will be a different non-terminating behavior if the captured key is 'p'?

If I change the condition to:

(info.KeyChar != 'q') && (info.KeyChar != 'p')

Then 'p' will also terminate the program. Even if I put logic inside the while loop to handle the 'p' case.

Also:

ConsoleKeyInfo info = Console.ReadKey(true);
while (true) {
    info = Console.ReadKey(true);
    if (info.KeyChar == 'q') break;
    else if (info.KeyChar == 'p') {
        //other behavior
     }
}

Requires the user to press 'q' twice to end the program for some reason, but the intended behavior is that the actions are triggered by one key press.

asked 7 mins ago

3 Answers

Vote count: 2

var exitWhile = false;
while (!exitWhile) {
    ConsoleKeyInfo info = Console.ReadKey(true);
    switch (info.KeyChar) {
        case 'q':
            exitWhile = true;
            break;

        case 'p':
            //something else to do
    }
}

answered 1 min ago

Vote count: 0

Because you called ReadKey twice, try this:

        while (true) {
            var info = Console.ReadKey(true);
            if (info.KeyChar == 'q') break;
            else if (info.KeyChar == 'p') {
                //other behavior
            }
        }

answered 2 mins ago

Vote count: 0

Personally, I'd go with something like this:

ConsoleKeyInfo info = Console.ReadKey(true);
bool done = false;
while (!done) {
    info = Console.ReadKey(true);
    switch(info.keychar) {
        case 'p':
            // do something
            break;
        case 'q':
            done = true;
            // do something else
            break;
    }
}

answered 20 secs ago

برچسب: نویسنده: استخدام کار تاريخ: چهارشنبه 13 مرداد 1395 ساعت: 8:45

صفحه بندی