Course contentsShow
← C
Lesson 434 of 1,2196. Arrays and StringsFree lesson

Removing newlines from `fgets` results

Removing newlines from fgets results

What you'll learn: How to clean up the trailing newline character that fgets automatically includes in your string.

The uninvited guest

When you use fgets() to read text from a user, it behaves like a very polite but literal assistant. If you ask it to read a name and the user types "Alice" followed by the Enter key, fgets grabs the letters 'A', 'l', 'i', 'c', 'e' and—crucially—the newline character (\n) created by that Enter key.

Think of it like ordering a pizza for delivery. You want the pizza, but the delivery driver also leaves the giant cardboard thermal bag on your kitchen counter. If you try to compare "Alice\n" to "Alice" later in your code, the computer will say they don't match. To fix this, we need to find that newline and swap it out for a null terminator (\0).

The "Find and Replace" strategy

To remove the newline, we use the strcspn function from the <string.h> library. This function searches a string for a specific character and returns the index (the position) where it first appears. If we look for \n, the function tells us exactly where that pesky Enter key character is sitting.

Here is how you safely strip the newline:

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

int main() {
    char name[50];

    printf("Enter your name: ");
    if (fgets(name, sizeof(name), stdin)) {
        // Find the newline and replace it with a null terminator
        // strcspn returns the length of the string before it hits a '\n'
        name[strcspn(name, "\n")] = '\0';
        
        printf("Hello, %s! Nice to meet you.", name);
    }

    return 0;
}

Why this works

The strcspn(name, "\n") trick is clever for two reasons. First, if the newline exists, the function returns its index, and we immediately overwrite it with \0, effectively shortening the string and cutting off the "tail."

Second, if the user typed a very long string that filled the entire buffer, there might not be a newline at all. In that case, strcspn returns the index of the existing null terminator. Overwriting a null terminator with another null terminator doesn't hurt anything. It’s a clean, one-line safety net that ensures your strings behave exactly how you expect them to during comparisons or printing.

Key takeaway

Always use strcspn to replace the trailing \n from fgets to prevent unexpected line breaks and matching errors in your data.