You are currently viewing How to Handle User Input in C with fgets

How to Handle User Input in C with fgets

fgets is a commonly used function in C for reading input from the user or from a file. It stands for “file get string” and is primarily used for reading text input.

The syntax of fgets is as follows:

char *fgets(char *str, int n, FILE *stream);

It’s important to note that fgets includes the newline character in the input if there is sufficient space in the character array. If the newline character is undesirable, it can be removed. The code provided demonstrates how to effectively use fgets to read user input in C and addresses the issue of removing the newline character that fgets captures when the user hits the enter button:

#include <stdio.h>
#include <string.h>

#define NAME_LENGTH 50

void stripLF(char text[]);

int main() {

    // define a character array to hold a name of not more than NAME_LENGTH characters
    char name[NAME_LENGTH];

    // prompt the user for their name
    puts("What is your name, human?");

    // get and store the user's name in the 'name' variable
    fgets(name, NAME_LENGTH, stdin);

    // since fgets captures the newline character, we need to remove it
    stripLF(name);

    // greet the user by printing their name
    printf("Hello, %s!\n", name);

    return 0;
}

void stripLF(char text[]) {

    // get the length of the string
    const size_t len = strlen(text);

    // remove any trailing newline characters ('\n')
    // at the end of the string
    while (text[len - 1] == '\n') {
        text[len - 1] = '\0'; // replace the newline with a null terminator
    }

}

We hope you found this code on fgets informative and helpful in your C programming journey. If you enjoyed this content and would like to receive more valuable resources, tips, and tutorials, we invite you to subscribe to our mailing list. By subscribing, you’ll stay up to date with the latest articles, code examples, and programming insights delivered directly to your inbox.

If you wish to learn more about C, please subscribe to our newsletter today and continue your C learning journey with us!

Leave a Reply