Equivalent to _kbhit () and _getch () in Ubuntu

0

People, In Windows I used to use the following code:

int userQuit = 0;

while (!userQuit)
{
    cout << "Algo acontece...\n";

if (_kbhit())
{
    char key = _getch();

    switch (key)
    {
        case 32:
        {
            cout <<"Continuar\n";           
            break;
        }
        case 27:
        {
            cout <<"Sair\n";
            userQuit = 1;
            break;
        }

    }
}
}

But I discovered that in Ubuntu there is no conio.h library, does anyone know of any way I can rewrite this code to work on Ubuntu ?

    
asked by anonymous 29.05.2018 / 22:01

1 answer

0

You can implement your kbhit like this:

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include "kbhit.h"

static struct termios initial_settings, new_settings;
static int peek_character = -1;

void init_keyboard()
{
    tcgetattr(0,&initial_settings);
    new_settings = initial_settings;
    new_settings.c_lflag &= ~ICANON;
    new_settings.c_lflag &= ~ECHO;
    new_settings.c_lflag &= ~ISIG;
    new_settings.c_cc[VMIN] = 1;
    new_settings.c_cc[VTIME] = 0;
    tcsetattr(0,TCSANOW,&new_settings);
}

void close_keyboard()
{
    tcsetattr(0,TCSANOW,&initial_settings);
}

/* Le o teclado sem bloquear o programa */
unsigned char kbhit()
{
    unsigned char ch;
    int nread;

    new_settings.c_cc[VMIN]= 0;
    tcsetattr(0,TCSANOW,&new_settings);
    nread = read(0,&ch,1);
    new_settings.c_cc[VMIN] = 1;
    tcsetattr(0,TCSANOW,&new_settings);
    if (nread==1)
    {
    return ch;
    }
    return 0;
}

kbhit.h :

#ifndef KBHITh
#define KBHITh

#ifdef __cplusplus
extern "C" {
#endif  // __cplusplus


void inti_keyboard( void );
void close_keyboard( void );
unsigned char kbhit( void );
int readch( void );


#ifdef __cplusplus
}
#endif  // __cplusplus

#endif

Usage:

init_keyboard();
while ( ( c= kbhit() ) != 'q' )
// ...
close_keyboard();
    
30.05.2018 / 14:57