Kfir
Kfir

Reputation: 157

Terminate user input (e.g., fgets()) when user presses ESC

I'm writing a simple C console application in Windows which gets user input in an infinite loop.

I want the application to be in "reading mode" and keep reading until the user presses a quit key (e.g. escape).

How can I both receive user input and terminate it when a specific special key is pressed?

Example:

while (1)
{
    // How do I stop loop and input with a specific key hit, e.g., ESC?
    fgets(buff, 255, stdin);
    printf("%s\n", buff);
}

Upvotes: 1

Views: 363

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172578

Your are probably looking for

while(!kbhit())

or you can use getch() included in the #include <conio.h> or getchar() included in the #include <stdio.h> usually used for Enter key.

Upvotes: 4

Related Questions