[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [G++ n00b] getche() in G++ ?
From: |
Lionel B |
Subject: |
Re: [G++ n00b] getche() in G++ ? |
Date: |
Fri, 2 Nov 2007 09:37:21 +0000 (UTC) |
User-agent: |
Pan/0.132 (Waxed in Black) |
On Thu, 01 Nov 2007 19:52:26 -0700, Paul Pluzhnikov wrote:
> Stefan Kristensen <stefan@jems.dk> writes:
>
>> My old school book has an example that uses getche(), which I
>> understand is not C++ standard and is not supported by G++. Can anyone
>> help me out and tell me what to use instead?
>
> getchar() is close, but not exactly equivalent. Reading keyboard
> *immediately* (without waiting for carriage return) is rather tricky on
> UNIX.
Indeed it is... I wrote this routine some time ago (works on Linux, not
sure about FreeBSD). It uses "termios" routines to put stdin
(temporarily) in "raw" mode:
#include <termios.h>
inline int getche()
{
termios settings;
const int fd = fileno(stdin);
if(tcgetattr(fd,&settings)<0) {
std::cerr << "error in tcgetattr\n";
return 0;
}
settings.c_lflag &= ~ICANON; // into "raw" mode
if (tcsetattr(fd,TCSANOW,&settings)<0) {
std::cerr << "error in tcsetattr\n";
return 0;
}
int c = getchar();
settings.c_lflag |= ICANON; // back to "canonical" mode
if (tcsetattr(fd,TCSANOW,&settings)<0) {
std::cerr << "error in tcsetattr\n";
return 0;
}
return c;
}
I'm sure it's not perfect, but it does the job for me...
Regards,
--
Lionel B