Merging multiple strings in c | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Merging multiple strings in c

Hi guys, I am facing a problem with merging strings in c language , I tried to do that with strcat function in a loop , the code below is not working as I want . See it and tell me were is the problem please and thanks a lot 💙 #include <stdio.h> #include <string.h> int main() { char txt[100]=""; char word[100]; int n; printf("Enter the length of words : "); scanf("%d\n", &n); for (int i=1; i<=n; i++){ scanf("%s\n", word); strcat(txt, word); } printf("%s", txt); }

3rd Sep 2022, 4:26 PM
Moha Riad
Moha Riad - avatar
1 Answer
+ 3
Can you clearly describe "but not as I wanted"? like how exactly you'd want it to work but it was giving you something else. I'm just asking for myself to understand better what the problem is. One thing I notice first is that the buffer is only 100 character long, what if user enters 2 for <n> and a 50 characters long input (or more) each time? did you anticipate that? What's the benefit from the use of '\n' in the conversion specifier used "%s\n" when reading <word>? I think you can instead limit the permitted <word> length, to prevent buffer overrun. (Edited)
3rd Sep 2022, 4:34 PM
Ipang