按c中的特定键停止无限循环或进程

stop infinite loop or process with press a specific key in c

我刚刚考虑过终端中的 ctrl+c,如您所知,它会停止每个进程、更新、无限循环等。然后我开始编写一个代码,以在无限循环并试图用特定的键停止它,但我不知道这怎么可能。

谁能帮我解决这个问题?

提前致谢

伙计,你可以这样做:

#include <stdio.h>
#include <conio.h>              // include the library header, not a standard library

int main(void)              
{
    int c = 0;             
    while(c != 'key that you want')             // until correct key is pressed
    {
        do {                
            //Fibonacci sequence
        } while(!kbhit());      // until a key press detected
        c = getch();            // fetch that key press
    }
    return 0;
}

使用 do while 可以,但您也可以使用布尔值来停止 while 循环。

#include <whateverHeaderYouUseToProcessInput.h>
#include <stdbool.h>

int main(void)
{
    bool running = true;

    while (running)
    {
        if (CheckIfKeyPressed(key))
             running = false;
    }

    return 0;
}