如何读取符号,直到从 cin 中按下 ESC 按钮C++

How to read symbols until ESC button is pressed from cin in C++

本文关键字:cin C++ 按钮 ESC 何读取 读取 符号      更新时间:2023-10-16

我需要让我的while循环工作,直到按下键盘上的ESC按钮。

char choose = NULL;
while( choose != 27)
{
    cout << "Choose (s), (e) or (n): ";
    cin.ignore();
    choose = cin.get();
    switch(choose){
    case 's': {SortRoutesByStartPoint(routeList, n); ShowRoutes(routeList, n, "Sorted list (s):"); break;}
    case 'e': {SortRoutesByEndPoint(routeList, n); ShowRoutes(routeList, n, "Sorted list (e):"); break;}
    case 'n': {SortRoutesByNumber(routeList, n); ShowRoutes(routeList, n, "Sorted list (n):"); break;}
    default: {cout << "Not foundnn"; break;}
    }
}

但是当我按下ESC按钮时,它什么也没发生。为什么?
如何让它工作?

简单的答案是,你不能,至少不可靠,使用标准流。 如果您输入自终端,您可以获得操作系统为您提供的东西。 总的来说,它在按下回车键之前不会给您任何东西,并且去除大量字符以进行行编辑和其他内容在此之前;ESC是其中之一,这是一个明显的变化字符。

当您想逐个字符阅读时(显然您显然做),你需要一些第三方库,比如诅咒。 或者你会有自己编写大量依赖于系统的代码。

#include <conio.h>
cout << "Choose (s), (e) or (n): ";
// cin.ignore();
// choose = cin.get();
choose =getche();
if(choice==0)  //an extended character code is next
  choice=getche();