【问题标题】:What does getch() in Turbo C return? I am sure they are not ASCII values for keys pressedTurbo C 中的 getch() 返回什么?我确定它们不是按键的 ASCII 值
【发布时间】:2014-07-30 19:16:28
【问题描述】:

Turbo C 中的 getch() 返回什么?我用它来初始化程序的箭头键,getch() 返回的值是 77、80、72 和 75,它们是字母的 ASCII 值,这清楚地表明它们不是 ASCII 值。如果它们不是 ASCII 值,那么它们是什么?

【问题讨论】:

  • 是什么让您认为箭头键不能返回字母字符?这一切都归结为终端仿真。
  • 两个键可以有相同的 ASCII 值吗?这是我的观点。
  • 可以从键盘发送超过 255 种不同的事件。这意味着某些击键将生成多字节输出。

标签: ascii turbo-c getch


【解决方案1】:

getch() 函数返回箭头键(和一些其他特殊键)的两个键码,它首先返回 0 (0x00) 或 224 (0xE0),然后返回一个标识所按下键的代码。

对于方向键,它首先返回 224,然后是 72(上)、80(下)、75(左)和 77(右)。如果按下数字键盘箭头键(关闭 NumLock),getch() 首先返回 0 而不是 224。

所以,你可以这样做:

char ch = getch ();
if (ch == 0 || ch == 224)
{
    switch (getch ())
    {
    case 72:
        /* Code for up arrow handling */
        break;

    case 80:
        /* Code for down arrow handling */
        break;

    /* ... etc ... */
    }
}

请注意,getch() 没有以任何方式标准化,这些代码可能因编译器而异。

【讨论】:

  • 这个答案有用吗?
【解决方案2】:

非标准conio.h中提供的getch()返回一个int:

#include <conio.h>

int     getch(void);

来自参考:

A single character from the predefined standard input handle is read and returned. 
The input is not buffered. If there is a character pending from ungetch 
(see section ungetch), it is returned instead. The character is not echoed to the 
screen. This function doesn't check for special characters like Ctrl-C.

If the standard input handle is connected to the console, any pending output in the 
stdout and stderr streams is flushed before reading the input, if these streams are 
connected to the console.

Return Value

    The character.

Portability

    ANSI/ISO C  No
    POSIX       No 

箭头键的问题在于它们不是单字节字符。为了处理箭头键,您必须处理 多字节 代码。您得到的数字只是密钥代码的两个字节之一。

有关阅读代码的示例,请参阅(How to read arrow keys) Cheat code in C programming (when inputted from the keyboard)

【讨论】:

  • 谢谢。但我想看看键返回的确切内容。如何实现多字节码?
  • 检查答案中的链接。
  • @MatinLotfaliee - 检查头文件:void delline(void); int getch(void); int getche(void);
  • @DavidC.Rankin - 是的。标头将返回值声明为整数。但你的参考资料说它是一个角色。此外,函数的名称表明您可以获取字符。顺便说一句,处理多字节代码需要在 Turbo C 中多次调用 getch,所以你的例子没用。
  • @MatinLotfaliee 你今天过得很糟糕吗?如果它让你感觉更好,请随时继续用答案发明问题。我不在乎。由于我没有提供示例,因此您关于它无用的尖刻评论是没有实际意义的。我敢肯定,在您对 C 的理解中,您知道“字符”由数值表示,而这些术语通常可以互换使用。如果您对参考有任何疑问,请使用参考来源Turbo C 提交错误。
猜你喜欢
  • 2019-02-12
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
相关资源
最近更新 更多