Removing a newline in C
The fgets function in C is annoying in that it copies a newline character to the buffer:
#include <stdio.h>
int main ( void )
{
char buffer[BUFSIZ];
printf ( "Enter a string: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL )
printf ( "|%s|\n", buffer );
return 0;
}
When you run this program and type "test", this is the output:
This is a good feature for dealing with long lines and such, but for the most part it serves only to frustrate beginners. Experienced programmers have learned to remove the newline with tricks such as:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char buffer[BUFSIZ];
printf ( "Enter a string: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
size_t len = strlen ( buffer );
if ( buffer[len - 1] == '\n' )
buffer[len - 1] = '\0';
printf ( "|%s|\n", buffer );
}
return 0;
}
Or more commonly:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char buffer[BUFSIZ];
printf ( "Enter a string: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
char *newline = strchr ( buffer, '\n' );
if ( newline != NULL )
*newline = '\0';
printf ( "|%s|\n", buffer );
}
return 0;
}
The annoying part of this issue is that one often is required to declare a variable, test for a newline character explicitly, and replace it explicitly. A quick timesaver when writing code is the strcspn function:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char buffer[BUFSIZ];
printf ( "Enter a string: " );
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
buffer[strcspn ( buffer, "\n" )] = '\0';
printf ( "|%s|\n", buffer );
}
return 0;
}
The downside to this timesaver is that it doesn't save time during execution. The strcspn trick will usually be slower than most other methods of removing a newline. However, because the performance hit of input far outweighs any difference in speed for removing the newline character.