【问题标题】:C program terminate while press escapeC程序在按下转义键时终止
【发布时间】:2018-12-25 08:17:33
【问题描述】:

我是 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;
}

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

【问题讨论】:

  • "当我按下 Escape 时什么都没有" --> 发布使用的示例输入 - 每按下一个键都会有所帮助。
  • Related answer,还有一个可能有用的search result
  • 这个问题的真正答案是“不要,这不是初学者的任务”。
  • 这与scanf无关。要扩展 n.m. 的评论(这不是初学者的任务),您需要意识到按下转义键会向操作系统发送中断,但根本不会向您的程序发送任何信息。要获取该信息,您需要根据所运行的平台执行不同的操作。 (但是,有些库可以抽象出差异。)与其在esc 上中止,不如在输入结束时终止程序更容易。这不仅更容易,而且更惯用且更有用。

标签: c loops for-loop while-loop terminate


【解决方案1】:

查看函数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;

    }
}

【讨论】:

  • 你能提供完整的程序吗??
  • @Md.ShamvilHossain 我做到了,我目前在我的智能手机上,所以我无法检查我上面的代码(但它应该可以工作)。
猜你喜欢
  • 2021-07-06
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多