调用 getch()读取扩展字符

最近翻阅简单的贪吃蛇代码发现这么一条代码,调用小键盘↑↓←→需要连续两次getch(),之前一般都是cin.get(),发现这么一个问题,找一下原因。

我们来做个实验:

#include <iostream>
#include <stdio.h>
#include <conio.h>

int main()
{
	while(1)
	{
		_getch();
		auto a = _getch();
		std::cout <<"a:"<< a << std::endl;
		auto b= _getch();
		std::cout << "b:" << b << std::endl;
	}

	return 0;
}

 我们按"↑",发现输出结果:

并且我们发现每次第三下都会自动输出下一个结果,例如按三下↑

第一下a:72、第二下b:224 第三下自动输出 a:224 b:72两项

这是怎么一回事呢?翻阅micsoft文档发现这么一句话

The _getch and _getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

These functions lock the calling thread and are therefore thread-safe. For non-locking versions, see _getch_nolock, _getwch_nolock.

_getch和_getwch函数从控制台读取单个字符而不回显字符。 这些函数都不能用于读取CTRL + C. 读取功能键或箭头键时,每个功能必须调用两次; 第一个调用返回0或0xE0,第二个调用返回实际的键代码。这些函数锁定调用线程,因此是线程安全的。对于非锁定版本,请参阅_getch_nolock,_ getwch_nolock

对比下其他的输入函数

  • getch():不从缓冲区读取数据,而是从键盘输入读取,虽然缓冲区刚开始有数据,但是它不读取,等待键盘输入读取,并且键盘输入的字符不会显示在屏幕上。
  • getche():将读入的字符回显到显示屏幕上
  • getchar():将读入的字符回显到显示屏幕上,等待输入直到按回车才结束,  回车前的所有输入字符都会逐个显示在屏幕上。但只有第一个字符作为函数的返回值。 
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值