简体   繁体   中英

C prompt user to press enter key and exit after one press

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?

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

You can also try this

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM