kbhit() with double loop not working well

2019-08-16 12:41发布

问题:

Just for fun, I tried printing kbhit() with loops, so that the program after a key press prints the line infinitely until pressed keyboard again. It compiles well and when run, just gives blank screen. No prints. But upon single keypress ends the program. The console does not close though.

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

int main()
{
  while(1)
  {
    if(kbhit())
    {
      while(1)
      {
        if(kbhit())
        {
          goto out;
        }
        printf("Print Ed Infinitum Until Key Press");
      }
    }
  }
  out:
  return 0;
}

How do I solve this?

回答1:

int main(void){
    while(1){
        if(kbhit()){
            getch();
            while(1){
                if(kbhit()){
                    getch();
                    goto out;
                }
                printf("Print Ed Infinitum Until Key Press\n");
            }
        }
    }
out:
    return 0;
}


回答2:

  1. The program begins
  2. No keys are present
  3. The second while doesn't execute
  4. It spins around in the first loop

You press a key:

  1. the first kbhit returns true
  2. It enters the second loop
  3. there is still a key present
  4. the second kbhit returns true
  5. the program exits

You need to remove the first keypress before entering the second loop and you should prompt yourself to press a key to begin the program. Or you could just jump into the second loop.