【问题标题】:stop infinite loop or process with press a specific key in c按 c 中的特定键停止无限循环或进程
【发布时间】:2020-11-22 21:57:08
【问题描述】:

我刚刚想到了终端中的ctrl+c,如您所知,它会停止每个进程、更新、无限循环等。然后我开始编写一个代码,在无限循环中打印斐波那契数列并尝试用一个特定的键来阻止它,但我不知道怎么可能。

谁能帮我解决这个问题?

提前致谢

【问题讨论】:

  • ISO C 标准本身的标准并不知道按键的概念。它只知道从流中读取输入的概念。因此,您将需要特定于平台的扩展来检测是否已按下某个键。因此,如果您想获得问题的答案,则必须指定问题适用的平台(例如通过设置适当的标签)。

标签: c key terminate


【解决方案1】:

你可以这样做:

#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;
}

【讨论】:

  • 请注意,函数 kbhitgetch 不是 ISO C 标准的一部分,而是特定于平台的扩展。例如,它们将在 Microsoft Windows 平台but not on the Linux platform 上工作。 OP 没有具体说明该问题适用于任何特定平台。所以你不能依赖这些可用的功能。
  • @AndreasWenzel 是的,没错
【解决方案2】:

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

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

int main(void)
{
    bool running = true;

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

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-27
    • 2015-03-22
    • 2015-02-07
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多