简体   繁体   中英

How to make C Program exit as soon as we enter a specific key?

#include <iostream>
#include <conio.h>

int main(){

    while(true){
        printf("Hello World!\n");
    }

    return 0;
}

The above program will print "Hello World" endlessly. I want that as soon the user presses the "T" key on the keyboard, the program terminates. Any clue on how to do this.......

If I do it like

#include <iostream>
#include <conio.h>


int main(){

    char key;
    while(true){
       printf("Hello World!\n");
        key = getch();
        if(key=='T' || key=='t'){
            break;
        }
    }

return 0;
}

Then the program will always wait for the user to press a key. I want that the program continues executing without pausing, and as soon as user presses any specific key, then the program terminates.

By the way my operating system is linux (debian) and I'm using gcc.

conio is Windows (OP tagged this as Linux). The question is frequently asked, usually answered pointing to termios , eg,

On the other hand, ncurses provides functions which are useful -- but unless you use filter , the screen will be cleared. Here are useful links for functions to consider:

By setting a short timeout (say 20 milliseconds), the program will respond faster than anyone's reaction time, and use little CPU.

Here is a revised program illustrating filter :

#include <ncurses.h>
#include <stdlib.h>

int
main(int argc, char **argv)
{
    int ch = 0;
    int n;
    int code;

    filter();
    initscr();
    timeout(20);
    for (;;) {
        move(0, 0);
        for (n = 1; n < argc; ++n) {
            printw("%s ", argv[n]);
        }
        printw("[y/n] ");
        clrtoeol();
        ch = getch();
        if (ch == 'Y' || ch == 'y') {
            code = EXIT_SUCCESS;
            break;
        } else if (ch == 'N' || ch == 'n') {
            code = EXIT_FAILURE;
            break;
        }
    }
    endwin();
    return code;
}

(Checking for y/n seems more useful than checking for "t" -- feel free to customize).

You can do a boolean checking before getting user input char getch() . this link explains well about it To see if user press a key

If you don't want to wait for keyboard input, there is unfortunately no standard way to proceed.

If your conio.h supports kbhit() just use it. Otherwise, for any linux and posix, you can look here for Morgan Mattews's code to provide the same functionality.

Your body of your loop would then look like this:

    ...
    if (kbhit()) {
        key = getch();
        if(key=='T' || key=='t'){
            break;
        }
    }

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