代码之家  ›  专栏  ›  技术社区  ›  Md. Shamvil Hossain

C程序在按escape时终止

  •  0
  • Md. Shamvil Hossain  · 技术社区  · 6 年前

    我是C的初学者。我在Windows上用Code::Blocks编写了一个C程序,它需要 int 输入并打印到下一行。我想运行循环直到我按下escape,但我不能这样做。我的代码是:

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

    回路正在工作。我输入一个整数,它在下一行打印它。但按escape键不会终止。当我按下Escape时什么都没有。我想运行这个程序直到我按下escape,同时仍然接受 内景 -键入来自用户的输入。如何在按escape时终止程序?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Alan    6 年前

    检查功能 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;
    
        }
    }