Fixing fgets() for Input

The fgets() function is a marvelous tool for reading chunks of text from the keyboard or standard input. One problem I have with it is that it also reads the Enter key press, sticking a \n into the string. That’s not a big issue, however, because you can easily pull out that character.

The newline is a required character for breaking standard input into chunks. It makes sense that fgets() would accept it and store it. Often times, however, you don’t want the newline stored as part of the input.

The solution is to code a function that modifies fgets()‘s behavior. The function needs to be passed the address of an input buffer and a length, similar to the original arguments for fgets(). The only thing you don’t need to pass is the file handle; for purposes of standard input, the stdin handle can be assumed.

I’ve named by substitute function input(), as shown in this code:

#include <stdio.h>

void input(char *string,int length);

int main()
{
    char firstname[32],lastname[32];

    printf("What is your first name? ");
    input(firstname,32);
    printf("What is your last name? ");
    input(lastname,32);
    printf("Please to meet you %s %s.\n",
        firstname,
        lastname);

    return(0);
}

void input(char *string,int length)
{
    int x;

    fgets(string,length,stdin);
    for(x=0;x<=length;x++)
    {
        if( string[x] == '\n')
        {
            string[x] = '\0';
            break;
        }
    }
}

The input() function at Line 20 serves as the surrogate for fgets(). In fact, fgets() is called immediately within the function, at Line 24. Then a for loop plows through input searching for the newline. Once found, it’s replaced with a null character, \0, at Line 29.

Remember: It’s possible that the input string may not contain a newline, which is why I chose to use a for loop and work through all of the input buffer.

Also see this post.

Leave a Reply