预打印C/C++中击键的ascii值

Prettyprint ascii values for keystrokes in C/C++

本文关键字:ascii 打印 C++      更新时间:2023-10-16

当我的程序的用户点击了一个未使用的键,甚至是一个没有可见字形的键时,我想报告类似"警告:忽略击键Ctrl+W"的内容。这比"忽略十进制值为23的击键;自己去谷歌吧,笨蛋。"更友善

那么,C或C++是否有任何模糊的标准方法来将int转换为字符串,比如这样?

65 -> "A"
141 -> "a"
32 -> "SPACE"
3 -> "CTRL+c"
26 -> "Ctrl+Z"

在EBCDIC衰落几十年后,复制粘贴诸如"man-ascii"这样的表太尴尬了(ascii值的名称)。

一个经典问题。

首先,我们需要对ASCII值和击键进行排序。ASCII是一种值为0到127的字符编码。击键"代码"各不相同,但通常在可用时映射到ASCII(Shift+A使ASCII代码为97),以及映射到其他键的其他代码或操作,如1。通常,键盘有超过256种可能的击键组合。此外,一些键盘接口可能直接生成Unicode,Unicode有超过一百万个代码。

典型地,char是8位(256个代码),并且通常将0到127编码为ASCII,其余部分非常依赖于系统。isprint()isgraph()可用于对"可视字形"要求进行排序。之后,可能需要推出自己的代码。

// Sample handler
int keystroke = OP_GetKeystroke();  // fictitious system dependent function
if (OP_IsChar(keystroke)) {
  char ch = keystroke;
  if (isascii(ch)) {
    if (isprint(ch)) {
      printf("%c", ch);
    }
    else if (ch < ' ') {
      printf("<Ctrl-%c>", ch+'@');
    }
    else {
      printf("<DEL>");
    }
  }
  else { 
    printf("<x%02X>", ch & 0xFF);  // char codes outside ASCII range 
  }
}
else {
  printf("<Key: %X>", keystroke);  // keystroke outside char range 
  }

对于ASCII代码32到126,isprint()为true。
对于与CCD_ 6期望代码32(空格)相同的代码,CCD_
这个答案在非ASCII环境中是有问题的。

如果您想要ASCII表中65的"A",请将int转换为(char):

#include <iostream>
using namespace std;
int main()
{
   int temp = 65;
   cout << (char)temp << endl; 
   return 0;
}