【问题标题】:Press Q to quit the loop [duplicate]按Q退出循环[重复]
【发布时间】:2017-04-26 02:22:01
【问题描述】:

我正在编写一个简单的代码,该代码每秒保持递增一个计数器,并且只有在按下“q”时才会停止递增。

我尝试了 getchar() 和 getline() ,但它们要求用户为每个循环输入一个输入。

为了更简单,这段代码一直依赖控制台,直到我通过 (Ctrl+c) 终止它,我想使用 'q' 来执行相同的功能。

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int j=0;
int main()
{
    printf("Enter Q to quit !\n");
    while(1)
    {
    j++;
    printf("%d\n",j);
    Sleep(1000);
    system("cls");
    }
    return 0;

}

【问题讨论】:

  • 我看到你使用的是 Windows,所以 MSVC 有 kbhit() 或 _kbhit() 来检测按键,之后你调用 getch() 或 _getch() 来获取按键。
  • 真的,“system("cls");”? 2016 年?

标签: c switch-statement


【解决方案1】:

我看到你使用的是 Windows,所以 MSVC 有 kbhit() 或 _kbhit() 来检测按键,然后你调用 getch() 或 _getch() 来获取按键。

#include <conio.h>
#include <stdio.h>
#include <windows.h>

int main()
{
    int j=0;
    printf("Enter Q to quit !\n");
    do {
        j++;
        printf("%d\n",j);
        Sleep(1000);
    } while (kbhit() == 0 || getch() != 'Q');
    return 0;
}

为什么while 不阻止getch?因为短路评估。如果kbhit == 0 为真,则不计算getch() != 'Q'。

【讨论】:

    【解决方案2】:

    您包含windows.h 的事实让我认为您正在寻找kbhit() 函数。从链接页面:

    此函数未定义为 ANSI C/C++ 标准的一部分。 Borland 的编译器系列通常使用它。如果键在键盘缓冲区中,则返回一个非零整数。它不会等待按键被按下。

    在 UNIX/Linux 上,您必须使用由@i_am_jorf 链接的answer 中所述的终端模式操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多