charcter input

Hi guys and girls;

I am writing a program for my college work and I am asking the user to input a single character using cin to capture the info.

Is there a way I can capture the keystoke rather than waiting for the user to press return.

What OS are you working on... I'm assuming Microsoft Windows?

for Windows I think there is something like
int kbhit(void)
in conio.h which returns the ASCII value of the key and 0 if nothing is pressed...
Your code might look something like this:
1
2
3
4
5
...
if (kbhit()) {
     /* Do Something */
}
...


Hope that helps... but I'm sure there's a more elegant solution for your problem...
And I have to say... It might not work with all compilers...
At least I know that it's used by the Borland ones...
Use libcurses. It works on both windows and UNIX. The ncurses implementation will likely only work on windows using Cygwin, but the pdcurses implementation works natively on windows.

pdcurses: http://pdcurses.sourceforge.net/

ncurses tutorial (probably compatible with pdcurses): http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/

If you want ncurses instead of pdcurses: http://www.gnu.org/software/ncurses/

To capture a keystroke (I assume you want the ASCII code and not the scancode), use the raw() function to disable line buffering and then use getch() to catch the key. I'd store it in an int and not a char incase you get an escaped character (they can be up to 4 bytes).
@Duoas,
There's an example in the link I gave (the ncurses HOWTO) which does exactly what the OP asked for and works on both windows and POSIX systems (and any system on which pdcurses and/or ncurses work).
Last edited on
@chrisname
Do you really believe that I am unfamiliar with ncurses?

NCurses might be overkill, that's all. The last link I gave shows how to get a single key using either Windows or POSIX.

Until the OP gives more info, posting the answers we have together covers all the bases.
@Duoas,
Of course not. I just didn't see the point of having to make two separate functions depending on which system you wanted to target -- using pd or ncurses, you only need one function regardless of what your target platform is. That's all.
But then your program requires ncurses
Topic archived. No new replies allowed.