I would like to writing a small C program that runs an infinite loop until the user presses a key on the keyboard (ie: there is a char in the stdin buffer). I am running into trouble breaking the loop on user input. I have tried using fgetc but that does not behave as expected. The code below waits for user input rather then running until user input.
Sample C Code:
while((c=fgetc(stdin) == EOF) {
/* Does stuff for infinite loop here */
printf("Example work in the loop\n");
}
printf("Out of the loop!\n");
How do I write a loop that executes until user intervention? Pressing any key or a specific key could be the intervention trigger.
Note 1: I am writing this for a Unix console in case of platform specific solutions
Note 2: Do not suggest Ctrl + C/X/Z as the user intervention trigger
This seems to work for me:
or you could use
select:Poll works too 🙂
One last way is to set the terminal in ‘raw’ mode. Note that this upsets output to the terminal (at least on mine on OS-X) in that \r becomes necessary after \n. Note also that it needs to be undone at the end (the terminating
tcsetattrcall). This is the only one that does not need a \n (ie any keypress will do)