Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Need help with user input (http://www.programmingforums.org/showthread.php?t=13114)

ZenOswyn May 5th, 2007 2:08 AM

Need help with user input
 
Hey all,
I'm making a small console game, and I'm looking for another way to get users input. I'm using the WASD keys to move a cursor on the screen, but the only way I know to get a users input is by using cin. As you can guess, having to press a direction key and then hit Enter is a bit time consuming on the users side and I was wondering if anyone can give me some help in finding another way to do this.

I know this can be accomplished using ncurses, and probably other libraries. But I'd really like to stick with the standard C++ libraries if possible.

Oswyn

grumpy May 5th, 2007 2:42 AM

Not possible. There is no way in the standard C or C++ libraries to receive individual keystrokes. That's because the standard libraries are based around a pretty generic computing device (and, generically, a computing device may not have a keyboard).

If you are targeting a machine with a keyboard, most compilers you will be using and their libraries include functions that provide some means of obtaining keystrokes directly. You need to read your compiler and library documentation to find out how to do it. Keep in mind that the method varies between compilers and systems. If you want to use curses or similar, look up raw input.

ZenOswyn May 5th, 2007 4:11 AM

I was afraid that would be the case. I looked over some curses examples and came up with this, a pretty minimal solution, in case anyone is interested.

:

#include <ncurses.h>

int main() {
        initscr();
        raw();
        noecho();
       
        char ch;
 
        while(!ch || ch != 'x') {
                ch = getch();
                printw("You pressed: %c \n", ch);
        }

        return 0;
}


grumpy May 5th, 2007 10:17 AM

Quote:

Originally Posted by ZenOswyn (Post 127519)
:

    char ch;
 
    while(!ch || ch != 'x') {


Technically, the above yields undefined behaviour (reading the value of an uninitialised variable yields undefined behaviour). To avoid that, initialise ch to zero (or to some value not equal to 'x') before the loop.


All times are GMT -5. The time now is 12:56 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC