Firstly, i must mention that i'm just learning about strings in C as a beginner. What i want to do is get 2 strings as input from an user and concatenate them. So here's what i did:
char firststring[40], secondstring[40];
printf ("Enter first string: ");
fgets (firststring, 40, stdin);
printf ("Enter second string: ");
fgets (secondstring, 40, stdin);
strcat(firststring, secondstring);
printf("%s", firststring);
The problem is that fgets also reads the newline character when the user inputs the first string so the output looks like this:
Hello
World
I tried to use puts
instead of fgets and it worked well, but too many people said NOT to use that function. Then i found out that i can use strcspn
after the first fgets
to remove the newline character, but that didn't gave me the one space i want between the words.
Desired output: Hello World
What i got: HelloWorld
Any suggestions how to do that?
You can do the following way
printf ("Enter first string: ");
fgets (firststring, 40, stdin);
printf ("Enter second string: ");
fgets (secondstring, 40, stdin);
size_t n = strcspn( firststring, "\n" );
firststring[n] = ' ';
strcpy( firststring + n + 1, secondstring );
provided that the firststring has enough space to append the string stored in the array secondstring.
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { N = 40 };
char firststring[N], secondstring[N];
printf( "Enter first string: " );
fgets( firststring, N, stdin );
printf( "Enter second string: " );
fgets( secondstring, N, stdin );
size_t n = strcspn( firststring, "\n" );
firststring[n] = ' ';
strcpy( firststring + n + 1, secondstring );
puts( firststring );
return 0;
}
Its output might look like
Enter first string: Hello
Enter second string: World!
Hello World!
A general approach to remove the new line character from a string entered by a call of fgets
is the following
string[ strcspn( string, "\n" ) ] = '\0';