Thread: Need help: wait for key press

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    2

    Need help: wait for key press

    I'm implementing the function that lets user set the control keys of the game. After the user clicks, it will wait until one key is pressed (without enter). I use kbhit() to wait for key press like this.

    Code:
    while(!kbhit()){}
    But even a key is pressed, it doesn't exit the loop. What's wrong with this?

    Appreciate all your help.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well you neglected to tell us which OS and Compiler you're using.

    How about the FAQ?
    http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2
    I use VC++ 2003 on Windows

  4. #4
    Registered User
    Join Date
    Apr 2005
    Posts
    1

    Lightbulb

    i have had slightly the same problem hours ago.
    i use the "Dev-C++ (Bloodshed) vers. 4.9.8.0" on a Windows XP machine.
    Code:
    if(kbhit())
    {
      i++;
    }
    instead of just executing the i++ one time it went on and on...

    so someone came up with this solution:
    kbhit() reads the keystroke into the buffer and doesn't
    delete it afterwards. a "fflush(stdin)" doesn't do the job, so a "getch()" is definitly necessary here.

    Code:
    if(kbhit())
    {
     getch();
      i++;
    }
    i'm sorry for any spelling mistakes for i am not a native speaker...

  5. #5
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    kbhit() only checks if a key has been pressed, getch() will return it's value. Also do note that these are conio.h functions and are outside of standard C.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-15-2008, 09:24 AM
  2. A key press funtion
    By getinhigh4life in forum Game Programming
    Replies: 3
    Last Post: 08-08-2008, 10:58 PM
  3. Wait for a specific key press (c++)
    By RazzTheKid in forum C++ Programming
    Replies: 6
    Last Post: 03-13-2008, 08:21 AM
  4. Replies: 2
    Last Post: 07-25-2003, 03:01 AM
  5. creating a wait funktion whitch will....
    By Shogun in forum C Programming
    Replies: 3
    Last Post: 04-11-2003, 02:35 PM