简体   繁体   English

按C键退出时C程序终止

[英]C program terminate while press escape

I am a beginner in C. I wrote a C program in Code::Blocks on Windows which will take a int input and print it on the next line. 我是C语言的初学者。我在Windows上的Code :: Blocks中编写了C程序,该程序将接受int输入并将其打印在下一行。 I want to run the loop until I press escape, but I can not do that. 我想运行循环,直到我按Escape键,但是我不能这样做。 My code is: 我的代码是:

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

The loop is working. 循环正在工作。 I input an integer and it prints it on the next line. 我输入一个整数,并将其打印在下一行。 But it is not terminating by pressing the escape key. 但这并不能通过按退出键来终止。 There is nothing when I press Escape. 当我按Escape键时,什么都没有。 I want to run the program until I press the escape, while still accepting int -type inputs from the user. 我想运行该程序,直到我按Escape键,同时仍然接受用户的int -type输入。 How can I terminate the program on pressing escape? 如何在按Escape键时终止程序?

Check out the function kbhit(); 检出功能kbhit(); and getch(); getch();

A possible solution would be: 可能的解决方案是:

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

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM