In addition to avoiding spaces between your two words, you also have to avoid the newline ('\n'
) character placed in the input buffer by the user pressing Enter. You can do that with a simple test after you have read the line with fgets()
NOT gets()
. gets()
is no longer part of the standard C library and should not be used due to insecurity reasons. Plus fgets
provides simple length control over the number of characters a user may enter at any time.
Below, you run into trouble when you read eingabe1
. After the read, eingabe1
contains a '\n'
character at its end. (as it would using any of the line-oriented input functions (e.g. getline()
, fgets()
, etc) To handle the newline, you can simply compare its length minus '1'
after you loop over the string to find the nul character. e.g.:
if (eingabe1[i-1] == '\n') i--; /* remove trailing '\n', update i */
By simply reducing the index 'i'
, this will guarantee that the concatenation with eingabe2
will not have any spaces or newline characters between the words.
Putting the pieces together, and using fgets
in place of the insecure gets
, after #define MAX 100
'ing a constant to prevent hardcoding your array indexes, you could come up with something similar to:
#include <stdio.h>
#define MAX 100
int main (void)
{
char eingabe1[MAX] = {0};
char eingabe2[MAX] = {0};
int i = 0;
int j = 0;
printf("Gib zwei Wörter ein, die aneinander angehängt werden sollen\n");
printf("1. Zeichenkette: ");
/* do NOT use gets - it is no longer part of the C library */
fgets(eingabe1, MAX, stdin);
putchar ('\n');
printf("2. Zeichenkette: ");
/* do NOT use gets - it is no longer part of the C library */
fgets(eingabe2, MAX, stdin);
putchar ('\n');
while (eingabe1[i]) i++; /* set i (index) to terminating nul */
if (i > 0) {
if (eingabe1[i-1] == '\n') i--; /* remove trailing '\n' */
while (i && eingabe1[i-1] == ' ') /* remove trailing ' ' */
i--;
}
while (eingabe2[j]) { /* concatenate string - no spaces */
eingabe1[i++] = eingabe2[j++];
}
eingabe1[i] = 0; /* nul-terminate eingabe1 */
printf("Nach Verketten: %s\n", eingabe1);
return 0;
}
Output
$ ./bin/strcatsimple
Gib zwei Wörter ein, die aneinander angehängt werden sollen
1. Zeichenkette: Lars
2. Zeichenkette: Kenitsche
Nach Verketten: LarsKenitsche
Let me know if you have any further questions. I have highlighted the changes with comments above.