Removing the newline from fgets
What you'll learn: How to cleanly swap the trailing newline character added by fgets for a null terminator to keep your strings tidy.
The unexpected guest
When you use fgets to read a line of text, it acts like a polite vacuum—it picks up everything you typed until you pressed Enter. However, there is a catch: fgets includes the Enter key (the \n newline character) as part of your string.
Imagine ordering a pizza and the delivery driver hands you the box, but they also leave their muddy shoes inside your hallway. You got the pizza you wanted, but now you have an extra mess to clean up. In C, if you type "Alice" and press Enter, fgets stores "Alice\n\0". If you try to print that name in the middle of a sentence, your text will suddenly break into a new line where you didn't want it.
The "Find and Replace" trick
To fix this, we need to find that \n and replace it with a null terminator (\0). This effectively tells C, "The string ends right here, just before the newline."
We use the strcspn function from the <string.h> library for this. This function searches a string and returns the index of the first character that matches any character in a given set.
#include <stdio.h>
#include <string.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
// strcspn finds the position of the '\n'
// We then overwrite that position with '\0'
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s! Nice to meet you.", name);
return 0;
}
Why this works
The strcspn(name, "\n") part calculates exactly how many characters exist before it hits a newline. If your string is "Alice\n", the newline is at index 5. By setting name[5] = '\0', you chop off the newline, leaving you with a clean "Alice".
If the user types a very long string that fills the buffer without a newline, strcspn will simply return the index of the existing null terminator, and you'll be replacing a \0 with a \0—which does no harm!
Key takeaway
Use name[strcspn(name, "\n")] = '\0'; immediately after fgets to strip away the trailing newline and keep your output formatted correctly.