John Smith John Smith - 4 months ago 14
C# Question

Two-condition While loop, one of which ends program

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.

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

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