Reputation: 597
I have a C program and as part of it I want to prompt the user to "press enter to continue" but I keep running into having to press the enter key twice. I want to detect a single enter key press. I saw this post Reading enter key in a loop in C and tried
char prev = 0;
while(1)
{
printf("Press enter to continue \n");
char c = getchar();
if(c == '\n' && prev == c)
{
break;
}
prev = c;
}
but that didn't work for me, still have to press enter twice, and prints the prompt twice. So then I just tried
while (1) {
printf("press enter to continue \n");
char prompt;
prompt = getchar();
if(prompt == 0x0A){
break;
}
}
but that still makes me press the enter key twice before moving on, though I only get the prompt once, so that is moving in the right direction. Any advice on a better approach?
Upvotes: 0
Views: 3070
Reputation: 319
You can also try this:
#include <stdio.h>
int main()
{
for(int prompt = 0; prompt != '\n' && prompt != EOF; prompt = getchar())
printf("press enter to continue \n");
}
Upvotes: 0
Reputation: 16540
instead of:
while (1) {
printf("press enter to continue \n");
char prompt;
prompt = getchar();
if(prompt == 0x0A){
break;
}
}
You might try (after emptying stdin
do
{
printf("press enter to continue \n");
int prompt = getchar();
} while( prompt != '\n' && prompt != EOF );
Upvotes: 2
Reputation: 445
char ch;
//infinite loop
while(1)
{
printf("Enter any character: ");
//read a single character
ch=fgetc(stdin);
if(ch==0x0A)
{
printf("ENTER KEY is pressed.\n");
break;
}
ch=getchar();
}
Upvotes: 1