Equivalent to _kbhit() and _getch() on Ubuntu

Asked

Viewed 40 times

0

Guys, No 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 library conio.h, someone knows some way I can rewrite this code to work on Ubuntu?

  • 1

    Search the Ncurses library

1 answer

0

You can implement your kbhit thus:

#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

Use:

init_keyboard();
while ( ( c= kbhit() ) != 'q' )
// ...
close_keyboard();
  • Thank you so much! It worked out here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.