kbhit() with double loop not working well

我的未来我决定 提交于 2019-12-13 07:03:55

问题


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.



来源:https://stackoverflow.com/questions/17263037/kbhit-with-double-loop-not-working-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!