【问题标题】:is there a way to make a festive tree like this in C?有没有办法在 C 中制作这样的节日树?
【发布时间】:2021-12-04 08:45:32
【问题描述】:

我想知道你是否可以在 C 上将这些单词重新排列成这种格式

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

这是我输入的代码,但它似乎不起作用:

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);

【问题讨论】:

  • 旁注:使用fgets(a, 50, stdin) 而不是gets(a),因为后者不会检查a 内是否有足够的空间来存储该行。 (这同样适用于其他 gets() 调用)。

标签: c algorithm


【解决方案1】:

不要在第一组字符串之前放置空格,而是在打印的第一个字符串上使用字段宽度。这将使给定长度的字段中的字符串右对齐:

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

【讨论】:

    【解决方案2】:
    #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("%10s|%s\n",a,a);
    printf("%10s|%s\n",b,b);
    printf("%10s|%s\n",c,c);
    printf("%10s|%s\n",d,d);
    return 0;
    }
    

    gets()fgets() 是 C 语言中的函数,用于输入字符之间有空格的字符串。 gets() 的问题在于它会遭受缓冲区溢出的影响,即它需要的输入比预期的要多。使用 fgets() 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多