【C++】利用_kbhit()和 _getche()非阻塞持续获取用户输入内容

两盒软妹~` 提交于 2020-02-19 11:39:32

  C++相关输入函数里_kbhit()可以非阻塞检查用户是否有输入,有返回一个非0值,否则返回0。
  而想获取用户输入的字符就需要获得键盘上读取到的字符,可以使用 _getche(),与 _getch()的区别是他可以回显用户的显示。

例子

  实现以下函数,持续获取用户输入字符串,遇到’Q’或者’q’时退出,每输入完一个字符串以回车结束。

#include <iostream>
#include <string>//字符串操作需要
#include <conio.h>//_kbhit()需要

int main()
{
	string sInput;
	while (true)
	{
		if (_kbhit())//非阻塞获取用户输入
		{
			char cTake = _getche();//获取输入字符,并回显		
			if (cTake == 'q' || cTake == 'Q')
			{
				break;
			}
			if (cTake == '\r')
			{
				cout << endl;
				cout << "Input message: "<< sInput << endl;
				sInput.clear();
				continue;
			}
			sInput = sInput + cTake;
		}
	}
	return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!