Home > Software engineering >  is there a way to make a festive tree like this in C?
is there a way to make a festive tree like this in C?

Time:10-17

i would like to know if you can re-arrange these words into this format on C

                  Jojo|Jojo
                    is|is
                   the|the
                  Best|Best
            Intheworld|Intheworld

this is the code that I have inputted but it doesn't seem to work:

char a[50],b[50],c[50],d[50];

gets(a);
gets(b);
gets(c);
gets(d);    
//tried to putt it into the middle with this string
a[strcspn(a, "\n")] = 0;
b[strcspn(b, "\n")] = 0;
c[strcspn(c, "\n")] = 0;
d[strcspn(d, "\n")] = 0;    
//this is how i print it
printf("    %s|%s\n",a,a);
printf("    %s|%s\n",b,b);
printf("    %s|%s\n",c,c);
printf("    %s|%s\n",d,d);

CodePudding user response:

Rather than putting spaces before the first set of strings, use a field width on the first string printed. That will right-justify the string in a field of the given length:

printf("@s|%s\n",a,a);
printf("@s|%s\n",b,b);
printf("@s|%s\n",c,c);
printf("@s|%s\n",d,d);

CodePudding user response:

#include <stdio.h>
#include <string.h>

int main()
{
char a[50],b[50],c[50],d[50];

fgets(a,50,stdin);
fgets(b,50,stdin);
fgets(c,50,stdin);
fgets(d,50,stdin);
a[strcspn(a, "\n")] = 0;
b[strcspn(b, "\n")] = 0;
c[strcspn(c, "\n")] = 0;
d[strcspn(d, "\n")] = 0;    

printf("s|%s\n",a,a);
printf("s|%s\n",b,b);
printf("s|%s\n",c,c);
printf("s|%s\n",d,d);
return 0;
}

gets() and fgets() are functions in C language to take input of string with spaces in between characters. The problem of gets() is that it suffers from buffer overflow that is it takes more input than it is supposed to take. This problem is solved using fgets().

  • Related