1

How do I read in the Enter key as an input in C? I'd like some program like this:

"Please enter a key to go to next line"

How do I add this type of option in C?

I am new to programming.

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265

4 Answers4

0

You can use the getc function in stdio.h to wait until a key is pressed. This C code will wait for the enter key to be pressed then output "Continued!":

#include <stdio.h>

int main(){
    printf("Press any key to continue");
    getc(stdin);
    printf("Continued!");
    return 0;
}
Justiniscoding
  • 441
  • 5
  • 19
0

If I understand your question, you can write:

printf("Press ENTER key to Continue\n");  
getchar();

Or

printf("Press Any Key to Continue\n");
getch();
Ali
  • 439
  • 1
  • 4
  • 14
0

A bunch of getc() demos in C:

1. To also print out what key was entered, do this:

read_in_any_key.c:

#include <stdio.h>

int main()
{
    printf("Press any key followed by Enter, or just Enter alone, to continue: ");
    int c = getc(stdin);
    printf("The first character you entered is decimal %i (\"%c\").\n", c, c);

    return 0;
}

Example runs and output. Notice in the last example I pressed Enter alone, so it printed it as a newline. The decimal numbers for each key can be found in an ASCII table, like this one: https://en.wikipedia.org/wiki/ASCII#Control_code_chart.

eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
Press any key followed by Enter, or just Enter alone, to continue: abc
The first character you entered is decimal 97 ("a").
eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
Press any key followed by Enter, or just Enter alone, to continue: def
The first character you entered is decimal 100 ("d").
eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
Press any key followed by Enter, or just Enter alone, to continue: FTL
The first character you entered is decimal 70 ("F").
eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_enter_key.c -o bin/a && bin/a
Press any key followed by Enter, or just Enter alone, to continue: 
The first character you entered is decimal 10 ("
").

2. To print out all of the keys typed, in case multiple keys were pressed before pressing Enter, do this:

read_in_any_key.c:

#include <stdint.h>  // For `uint8_t`, `int8_t`, etc.
#include <stdio.h>   // For `printf()`

// int main(int argc, char *argv[])  // alternative prototype
int main()
{
    printf("Press any key followed by Enter, or just Enter alone, to continue: ");
    int c = getc(stdin);
    printf("The first character you entered is decimal %i (\"%c\").\n", c, c);

    // If you entered one or more characters above before pressing Enter, they
    // are still in the stdin input stream's buffer, so let's read those out
    // too, up to the newline char (`'\n'`) created by pressing Enter.
    uint32_t charNum = 2;
    while (c != '\n')
    {
        c = getc(stdin);
        if (c == EOF)
        {
            printf("Failed to get char!\n");
            break;
        }
        printf("char %-2u = decimal %i (\"%c\").\n", charNum, c, c);
        charNum++;
    }

    return 0;
}

Example run and output. I typed abcdefghijklmnop and then pressed Enter:

eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_in_any_key.c -o bin/a && bin/a
Press any key followed by Enter, or just Enter alone, to continue: abcdefghijklmnop
The first character you entered is decimal 97 ("a").
char 2  = decimal 98 ("b").
char 3  = decimal 99 ("c").
char 4  = decimal 100 ("d").
char 5  = decimal 101 ("e").
char 6  = decimal 102 ("f").
char 7  = decimal 103 ("g").
char 8  = decimal 104 ("h").
char 9  = decimal 105 ("i").
char 10 = decimal 106 ("j").
char 11 = decimal 107 ("k").
char 12 = decimal 108 ("l").
char 13 = decimal 109 ("m").
char 14 = decimal 110 ("n").
char 15 = decimal 111 ("o").
char 16 = decimal 112 ("p").
char 17 = decimal 10 ("
").

3. To only continue if Enter is pressed alone, with nothing else before it, do this:

read_until_only_enter_key.c:

#include <stdbool.h> // For `true` (`1`) and `false` (`0`) macros in C
#include <stdio.h>   // For `printf()`

// Clear the stdin input stream by reading and discarding all incoming chars up to and including
// the Enter key's newline ('\n') char. Once we hit the newline char, stop calling `getc()`, as
// calls to `getc()` beyond that will block again, waiting for more user input.
void clearStdin()
{
    // keep reading 1 more char as long as the end of the stream, indicated by the newline char,
    // has NOT been reached
    while (true)
    {
        int c = getc(stdin);
        if (c == EOF || c == '\n')
        {
            break;
        }
    }
}

// Returns true if only Enter was pressed, and false otherwise
bool getOnlyEnterKeypress()
{
    bool onlyEnterPressed = false;
    printf("Press ONLY the Enter key to continue: ");
    int firstChar = getc(stdin);
    if (firstChar == '\n')
    {
        printf("Good! You pressed ONLY the Enter key!\n");
        onlyEnterPressed = true;
    }
    else
    {
        printf("You failed. You pressed another key first.\n");
        clearStdin();
    }
    return onlyEnterPressed;
}

// int main(int argc, char *argv[])  // alternative prototype
int main()
{
    while (!getOnlyEnterKeypress()) {};

    return 0;
}

Example run and output. Notice that the program didn't exit until the very end when I presed only Enter, withOUT more keys before it first.

eRCaGuy_hello_world/c$ gcc -Wall -Wextra -Werror -O3 -std=c17 read_until_only_enter_key.c -o bin/a && bin/a
Press ONLY the Enter key to continue: a
You failed. You pressed another key first.
Press ONLY the Enter key to continue: abc
You failed. You pressed another key first.
Press ONLY the Enter key to continue: w
You failed. You pressed another key first.
Press ONLY the Enter key to continue:
Good! You pressed ONLY the Enter key!

If you'd like to read keypresses instantly, rather than waiting for the Enter key to be pressed, see the link at the top of the "Going Further" section just below.

References:

  1. Answer by @Justiniscoding
  2. https://en.cppreference.com/w/c/io/fgetc
  3. https://www.cplusplus.com/reference/cstdio/getc/

Related/Going Further:

  1. [my answer] How to read keypresses instantly rather than waiting for Enter: Capture characters from standard input without waiting for enter to be pressed
  2. What is the equivalent to getch() & getche() in Linux?
  3. How to avoid pressing Enter with getchar() for reading a single character only?
  4. Read Key pressings in C ex. Enter key
Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
0

Only one other answer properly touches on this. Do not assume your user will obey you, even if he or she intended to.

// Ask user to do something
printf( "Press Enter to continue: " );
fflush( stdout );

// Wait for user to do it
int c;
do c = getchar();
while ((c != EOF) and (c != '\n'));

This discards other input until the Enter key is pressed or EOF is reached, leaving your input stream in a known state.

If you wish to have unbuffered input, that is a whole different can of worms.

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39