5

I'm trying to make a little console program that will basically be console pong. So right now I have this:

int main()
{
    while(1)
    {
        clearScreen();
        restThread(100);
    }
    return 0;
}

The only input I need to poll is if the user has pressed the A or D key since the screen was cleared. I will also need to know when the key is released. I'm also trying to do this cross platform.

so really all I need is like an if(keyWasDown('a')) {} sort of function.

Thanks

1
  • 1
    There's no standard way. Any answers you get are going to be platform-specific. Commented Jan 21, 2011 at 1:17

2 Answers 2

8

Maybe you want kbhit (non-blocking) or getch (blocking), both from <conio.h>. There's also getchar, from <stdio.h> or <cstdio>.

If you want the program to wait for a keyboard press, getch or getchar by themselves will do.

If you don't want the program to wait for a keyboard press, kbhit combined with either getch or getchar will suffice.

However, as GMan said, these methods are not really cross platform (if you never intend to try this on different platforms, that's moot, really). For console games, you might be interested looking into ncurses.

Sign up to request clarification or add additional context in comments.

1 Comment

At least Windows. I know it doesn't work on my Linux machine.
3

#include <stdio.h>
#include <conio.h>

int main()
{
    while(1)
    {
        clearScreen();

        if(kbhit())
        {
            int const ch = getch();
            switch(ch)
            {
            case 0x61: printf("A was pressed!\n"); break;
            case 0x64: printf("D was pressed!\n"); break;
            }
        }

        restThread(100);
    }

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.