+ 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); }
1 ответ
+ 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)