C - Is there a way to read a single character of user input, and not have the rest "pushed down" to the next request for input?

Related searches

So, I'm working on a simple hangman game in C, and I have the function read_guess, shown below.

void read_guess(char *guesses, char *p_current_guess)
{
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
        printf(">>> ");
        fgets(p_current_guess, 2, stdin);

        if (!isalpha(*p_current_guess)) printf("Guesses must be alphabetic. Please try again.\n\n");
        else
        {
            valid_guess = 1;

            // Iterates over array of guesses and checks if letter has already been guessed
            for (int i = 0; guesses[i] != '\0'; i++)
            {
                if (guesses[i] == *p_current_guess)
                {
                    printf("You have already guessed this letter. Please try again.\n\n");
                    valid_guess = 0;
                    break;
                }
            }
        }
    }
}

I've tried all the standard input functions (including getchar), but with all of them, when an input larger than one character is supplied, instead of taking just the first character and moving on (or asking again), the rest of the input is "pushed back", and the next time input is requested, whether it be because the input contained a non-alphabetic character or the next round begins, the rest of the input is automatically processed. This repeats for each character of the input.

How can I avoid this?


You are using fgets which is good, but unfortunately not the right way...

fgets reads up to an end of line or at most 1 less the the number of character asked. And of course remaining characters are left for the next read operation...

The idiomatic way would be to ensure reading up to the end of line, whatever the length, or at least up to a much larger length.

  1. Simple but could fail in more than SIZE characters on input:

    #define SIZE 64
    ...
    
    void read_guess(char *guesses, char *p_current_guess)
    {
        char line[SIZE];
        int valid_guess = 0;
    
        // Repeatedly takes input until guess is valid
        while (valid_guess == 0)
        {
            printf(">>> ");
            fgets(line, SiZE, stdin);                // read a line of size at most SIZE-1
            p_current_guess[0] = line[0];            // keep first character
            p_current_guess[1] = '\0';
            ...
    
  2. Robust but slightly more complex

    /**
     * Read a line and only keep the first character
     *
     * Syntax: char * fgetfirst(dest, fd);
     *
     * Parameters:
     *  dest: points to a buffer of size at least 2 that will recieve the
     *         first character followed with a null
     *  fd  : FILE* from which to read
     *
     * Return value: dest if one character was successfully read, else NULL
     */
    char *readfirst(dest, fd) {
    #define SIZE 256              // may be adapted
        char buf[SIZE];
        char *cr = NULL;          // return value initialized to NULL if nothing can be read
        for (;;) {
            if(NULL == fgets(buff, sizeof(buff), fd)) return cr; // read error or end of file
            if (0 == strcspn(buff, "\n")) return cr;             // end of file
            if (cr == NULL) {                                    // first read:
                cr = dest;                        //  prepare to return first char
                dest[0] = buff[0];
                dest[1] = 0;
            }
        }
    }
    

    You can then use it simply in your code:

    void read_guess(char *guesses, char *p_current_guess)
    {
        int valid_guess = 0;
    
        // Repeatedly takes input until guess is valid
        while (valid_guess == 0)
        {
            printf(">>> ");
            fgetfirst(p_current_guess, stdin);
    

A beginners' guide away from scanf(), C is a very low-level language and one consequence of that is the following: Rule 1: scanf() is not for reading input, it's for parsing input. #include <stdio.h> int main(void) { char name[12]; printf("What's your name? So you have a way to check whether the whole string was converted. base allows you� Code three consecutive getchar() functions to read the characters. Format the result like this: The three characters are 'a', 'b', and 'c' where these characters — a, b, and c — would be replaced by the program’s input. The program you create in Exercise 4 waits for three characters.


You can discard all input until end-of-line, each time you want to ask for input.

void skip_to_eol(FILE* f, int c)
{
    while (c != EOF && c != '\n')
        c = fgetc(f);
}
...
    char c = getchar(); // instead of fgets
    skip_to_eol(stdin, c);

How do I avoid a "dangling" newline when reading single character , To get a single character from the user in C, many beginning If you don't remove the newline character from the input stream, it could interfere� Read a character in C#: Here, we are going to learn how to read a character by using different methods in C#? Submitted by IncludeHelp, on April 07, 2019 . As we know that, Console.ReadLine() is used for input in C#, it actually reads a string and then we convert or parse it to targeted type.


You can use getch() function on windows to get single character. and this is linux equivalent

What is the equivalent to getch() & getche() in Linux?

Loops and Strings | Think Java, Repeating tasks without making errors is something that computers do well and Another way to read nested loops, like the ones in this example, is: “For each row user input as in Section 5.9, it's impossible to know how many times the user will To search for a specific character in a string, you could write a for loop and� Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()).I know there's a function in Windows for it, but I'd like something that is cross-platform.


Character Input (The GNU C Library), This section describes functions for performing character-oriented input. that the result is not EOF , you can be sure that it will fit in a ' char ' variable without loss of information. optimized, so it is usually the best function to use to read a single character. c = tolower (fgetc (stdin)); answer = c; /* Discard rest of input line. The original idea that I had was to read the text stream from the user into an array declared to size of 1, ignoring all other characters after the first character so as not crash the program. There HAS to be a better way of doing this.


Forms in HTML documents, If a control does not have an initial value, the effect of a form reset on that control is Authors create buttons with the BUTTON element or the INPUT element. i.e., the server is able to accept any single character encoding per entity received. Please consult the section on form submission for information about how user� Another important detail is that if you’re looking to read one character and not one byte, you should read 4 bytes from the input stream, as that’s the maximum number of bytes a single character will consist of in UTF-8 (Python 3+). Reading only a single byte will produce unexpected results for multi-byte characters such as keypad arrows.


This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen. The int putchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time.