Clear the input buffer - c

I am trying to implement the press any key to continue function by using kbhit, however, after the user presses a key for example a, it will appear in the input buffer the next time I ask the user to input a value. How do you clear the input buffer?
my code for press any button to continue is below.
void
press_any_key(void)
{
int b=0;
while (b==0)
{
b=kbhit();
}
}

I'm trying to implement the press any key to continue function by using kbhit taking this statement as a need to wait for user keyboard input to continue the program execution the below code does the job,
void press_any_key(void)
{
while(1)
{
if(kbhit())
ch = getch();
printf("You passed %c\n", ch);
}
}
Note: the above snippet doesn't try to clear the input buffer. However kbhit() is non standard instead the right way is to read a character from stdin is using fgetc.

Related

Prompt User to press enter to continue

I'm having trouble getting my program to accept hitting the enter key to continue... I tried getchar() two ways (as condition for while loop and just calling the routine) but one doesn't pause the program and await input it just goes through it all and the other pauses but wont let me enter anything or continue when i hit enter...
void RestOfGame(int r, int c, int mG, int **cGen,int **nGen) {
int i = 0, q = 0;
for (i = 2; i <= mG; i++) {
printf("\n(press enter to continue)\n\n");
getchar();
printf("Generation %d:\n", i);
ExamineReplace(r, c, cGen, nGen);
NewToOld(r, c, cGen, nGen);
DrawGrid(r, c, cGen);
}
}
I read in a few other threads something about having previously scanned in something and the buffer keeping the \n... tried some variations but I dont think i did it right.
Working on a windows platform, C language.
Any suggestions?
UPDATE: Thought I might add that this code is being run with a data file as input in redirection at command line. Would confuse my getchar() even though I've read through the entire file?
Use of the GetAsyncKeyState() function from the Windows.h header file allows us to check if a key has been pressed or currently being pressed.
So create a loop that checks the key state until it detects that it has been pressed.
which I have done in the wait_key() function
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#define UNUSED(x)((void)(x))
// Function that waits for key press
static inline void wait_key(const int vKey, const char* const phrase) {
// Display user message
puts(phrase);
// Wait until key is pressed
while (!GetAsyncKeyState(vKey))
Sleep(100);
}
int main(const int argc, const char** argv) {
UNUSED(argc); UNUSED(argv);
// VK_RETURN = enter key : https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
// Wait until enter key is pressed
wait_key(VK_RETURN, "Press enter to continue...");
return (int)EXIT_SUCCESS;
}
If you simply want to wait and have the user to press Enter to continue, then use fgets() and a short buffer. fgets() will block until input is received and will read and include the '\n' (generated by pressing Enter) in the buffer it fills.
You must be mindful of the state of stdin before you call fgets() (e.g. if a prior read with scanf and "%d" has left a '\n' in stdin unread, then it will appear that fgets() was skipped)
Your function above and be re-written as follows to wait until the user presses Enter
void RestOfGame (int r, int c, int mG, int **cGen,int **nGen)
{
int i = 0, q = 0;
for (i = 2; i <= mG; i++) {
char buf[128]; /* short buffer for fgets */
printf("\n(press enter to continue)\n\n");
fgets (buf, sizeof buf, stdin); /* fgets for input */
printf("Generation %d:\n", i);
ExamineReplace(r, c, cGen, nGen);
NewToOld(r, c, cGen, nGen);
DrawGrid(r, c, cGen);
}
}
Above, buf is a short 128-char buffer that will handle the Enter as well as 126 other slips of the finger before Enter and continue working fine.

How to repeat a process in a while until enter is pressed?

I need to repeat a process and I'm using a while. I need to do antoher process when enter key is pressed and I'm using if(getchar()). The problem is that the while "pauses" when it gets to the if because it's checking if getchar() it's true. I need to know how to keep looping the while whithout it stopping to check if there's an enter.
I'm making a game in which you have 1 minute to guess as much names as you can. So the purpose of the while() is to countdown from 60 to 0 seconds (clears the screen and prints the new second and the name you're actually guessing every second). So I want it to keep running the while() so the timer keeps running, but if enter is pressed it only changes the guessed name to a new name and the timer keeps running. (I don't know if I was clear but this is the idea)
//program in c
while(//specific condition)
{
/*- here goes the code for a timer that every second it clears the
- terminal and prints the next number (in seconds).
-
-
-*/
if(getchar()) //the current program stops here and keeps running the loop
//until enter is pressed
{
//second process
}
}
I expect the while to keep looping until there's an enter. When that happens I want it to enter the if, exit the if and keep looping.
char buffer[100];
while (fgets(buffer, sizeof(buffer), stdin))
{
if (strlen(buffer) == 1)
break;
if (sscanf(buffer, "%f", &f) == 1)
{
total += f;
printf("Enter another number: ");
}
}
if you have conio.h available in your environment you can use kbhit
while(//specific condition)
{
/*--process to do
-
-
-
-*/
if(kbhit())
{
if (getchar() == 0x0d)
{
break;
}
}
//second process
}
In this loop, the second process will run without checking the enter key and only exit if enter key is pressed.
You cannot use if(getchar()=='\n')
so the program runs until an enter key is pressed
because buffer value of '\n' will be present and it'll alter the next iteration
char a;
printf("Enter charecter or press enter to exit:");
scanf("%c",&a);
while(1)
{
//process 1 loop
if (a == '\n')
{
// process 2 here, if process two has loop make it's own loop here
printf("we are in process 2\n");
break;
}
getchar();
printf("Enter charecter or press enter to exit:");
scanf("%c",&a);
}
You did't give enough code to understand what input stream you are working with but something like this will do it, if it's file stream or string do it accordingly by replacing scanf with fgets, or file stream inputs like fscanf or fread.

Print every character the user types without conio.h

I want to make a program that runs forever and takes a user input, something like
while(1)
{
if(currentkeybeingpressed != NULL)
{
print(the current character); /* So that the program just waits until a key is
pressed and outputs the same letter the moment it is touched*/
}
}
I want to do this on a KISS controller, which does not have the conio.h file ready to import and therefore I cannot use the getch function. Is there another way to find out what key is being pressed at the moment?
#include<stdio.h>
int main() {
while(1){
putchar(getchar());
}
}
Hope this helps.

exit a loop by taking esc as input from user [duplicate]

This question already has an answer here:
Read user input until ESC is pressed in C
(1 answer)
Closed 6 years ago.
let say i'm in an infinite while loop and i want the user to enter the data in integer form. Then the data will be passed to another function for some other purpose this process will keep continuing until the user input esc in the place of data and i want the loop to break at that point. how should i do that?
while(1)
{
printf("enter the data that need to entered\npress esc to exit\n");
scanf("%d",&n);
function(n);
}
i tried to use if-else but if i put the ascii value of esc as the data input it exits the loop which i don't want to happen?
As dingrite wrote in his other answer:
Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent.
No other way exists to achieve the desired result, the cin approach has its problems - such as the application must be in focus.
Take a look at this question: C++: execute a while loop until a key is pressed e.g. Esc?
Or you can try with this example found on other page
#include <stdio.h>
int main (void)
{
int c;
while (1) {
c = getchar(); // Get one character from the input
if (c == 27) { break; } // Exit the loop if we receive ESC
putchar(c); // Put the character to the output
}
return 0;
}
Hope this helps.

Capturing a user's "enter" keystroke in C

I'm starting to learn C now and i'm trying to figure out how I would go about capturing when the user hits "enter." I'm looking particularly at the scanf and getc functions but I'm not quite sure how to go about it. When the user hits enter I want to perform some operations while waiting/watching for him to hit enter again... Is "enter" a new line character coming in from the console? Any advice would be much appreciated!
You can check the ascii value using fgetc().
while(condition) {
int c = fgetc(stdin);
if (c==10) {//Enter key is pressed
//your action
}
}
If you just need the input when user presses enter as input you can use scanf or getchar. Here is an example from cplusplus.com
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
This code prints what you entered to stdin (terminal window).
But if you do not want the input ( i know it's really unnecessary and complicated for a new learner) you should use an event handler.
printf("Hit RETURN to exit"\n");
fflush(stdout);
(void)getchar();
Ref: comp.lang.c FAQ list ยท Question 19.4b
The C language is platform-independent and does not come with any keyboard interaction on its own. As you are writing a console program, it is the console that processes the keyboard input, then passes it to your program as a standard input. The console input/output is usually buffered, so you are not able to react to a single keypress, as the console only sends the input to the program after each line.
However! If you do not demand your console application to be platform-independent, there is a non-standard library <conio.h> in some Windows compilers that has a function called getche();, which does exactly what you want - wait for a single keypress from the console, returning the char that was pressed.

Resources