C 程序在按 escape 时终止

标签 c loops for-loop while-loop terminate

我是 C 语言的初学者。我在 Windows 上的 Code::Blocks 中编写了一个 C 程序,它将接受 int 输入并在下一行打印它。我想运行循环直到按转义键,但我不能这样做。我的代码是:

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

int main(void)
{
    int k;
    do {
        scanf("%d",&k);
        printf("%d\n", k);      // print  value
    } while (k != 27);          // end when Esc pressed

    return 0;
}

循环正在运行。我输入一个整数,它会在下一行打印它。但按退出键并不会终止它。当我按 Esc 键时什么也没有。我想运行该程序,直到按下转义键,同时仍然接受用户的 int 类型输入。如何在按转义键时终止程序?

最佳答案

查看函数 kbhit();getch();

一个可能的解决方案是:

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

int main(){

char ch;
int k;
while (1) {

    if (kbhit) {

        scanf("%d",&k);
        printf("%d\n", k); 

        // Stores the pressed key in ch
        ch = getch();

        // Terminates the loop
        // when escape is pressed
        if (int(ch) == 27)
            break;

    }
}

关于C 程序在按 escape 时终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51384597/

相关文章:

javascript - 我如何将这个 for 循环变成 forEach 循环?

python - 查找列表中的值是否大于其下方的项目

在单个 "for"循环中计算阶乘以计算级数和

C:递归计算矩阵行列式的程序

c - uint8_t 中的二进制序列

c - XCode 5.1 中的 "' portaudio.h ' file not found"错误

c - malloc 返回类型转换困惑

php - 为什么我无法访问该关联数组中的该值/元素?

Javascript - Tic Tac Toe - 如何遍历获胜条件?

JavaScript - myArray.forEach 与 for 循环的细微差别