Reputation: 13
I tried using getch() and kbhit() to read user's input but it doesn't seem to recognise that a key was pressed.
void main(){
printf("start\n");
while (1){
if (kbhit() == 1){
printf("in\n");
int k = getch();
printf("k: %d\n", k);
}
}
}
This code prints "start" and doesn't print anything when a key is pressed. I had no luck using getch() to read and print even one character, without the loop.
Upvotes: 1
Views: 1214
Reputation: 16540
The posted code does not compile!
There are only 2 valid signatures for main()
, regardless of what visual studio might allow:
int main( void )
int main( int argc, char *argv[] )
Notice they both return a int
, not a void
the posted code is missing the necessary #include
statements
when asking a run time question, as this question is doing, post a [mcve] so we can recreate the problem.
the function: kbhit()
returns a non-zero value (not necessarily 1) when a key is pressed.
Suggest:
#include <stdio.h>
#include <conio.h> // note: this is a nonstandard header
// in Windows, so it is not portable
int main( void )
{
printf("start\n");
while (1)
{
if ( kbhit() )
{
printf( "in\n" );
int k = getch();
printf( "k: %d\n", k );
}
}
}
Upvotes: 1