// ************************************************** // PROGRAMAÇÃO DE SOFTWARE BÁSICO // // Arquivo: mygetch.cpp // // Autor: Rafael Rieder // Email: rafaelrieder@yahoo.com.br // // Descrição: // Exemplo de programa que lê um caractere do // teclado e o processa, sem a necessidade de // pressionar ENTER. // Este programa foi testado com o compilador G++, // tanto em ambiente Windows quanto em Linux. // // O código foi baseado na página: // http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1042856625&id=1043284385 // ************************************************** #include #ifdef WIN32 // compila para o Windows #include #include // para glibc #include #else // compila para Linux #include // para glibc #include #endif using namespace std; /* Function int mygetch() This code sets the terminal into non-canonical mode, thus disabling line buffering, reads a character from stdin and then restores the old terminal status. For more info on what else you can do with termios, see "man termios". There's also a "getch()" function in the curses library, but it is /not/ equivalent to the DOS "getch()" and may only be used within real curses applications (ie: it only works in curses "WINDOW"s)... Source: http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?answer=1042856625&id=1043284385 */ #ifndef WIN32 int mygetch() { struct termios oldt, newt; int ch; tcgetattr( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); return ch; } #endif int main(void) { unsigned char ch; cout << "Pressione * para sair..." << endl; cout << endl; do { cout << "Entre com um caractere qualquer: "; #ifdef WIN32 ch = (unsigned char)getch(); #else ch = mygetch(); // para ambientes UNIX #endif cout << endl; cout << "Você pressionou a tecla........: " << ch << endl; } while (ch != '*'); system("PAUSE"); return 0; }