문제

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?

도움이 되었습니까?

해결책

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;
}

다른 팁

  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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top