0

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?

djf
  • 6,592
  • 6
  • 44
  • 62
user2178841
  • 849
  • 2
  • 13
  • 26
  • 1
    [Don't use gotos](http://xkcd.com/292/) (Also, you probably mean "ad infinitum" ;)) – Kninnug Jun 23 '13 at 16:56
  • no, there are few places where many users here have adviced to use goto. I explored http://stackoverflow.com/questions/245742/examples-of-good-gotos-in-c-or-c, and other few posts. – user2178841 Jun 23 '13 at 17:09
  • 1
    In this case you can easily avoid the `goto` by just returning immediately in the `if`. If you have to do more clean up before exiting a `goto` might be more justified. – Kninnug Jun 23 '13 at 17:16

2 Answers2

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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
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.