【问题标题】:Format a string into columns in C将字符串格式化为 C 中的列
【发布时间】:2017-03-25 22:18:14
【问题描述】:

不管每个字符串的大小如何,我都无法让这个字符串均匀地分布在列中。我尝试了不同的格式和其他东西;它只是不工作。该函数的工作方式是,在 printCompanyTable 工作之前,还有另一个函数可以更新您在下面看到的所有字符串变量,所以我猜这可能是问题所在。

int printCompanyInfo() {  // this will print out the format for as long as I need it.
    char discount[30];
    char tax[30];
    if (discountTypeLookup == 0) {
        strcpy_s(discount, 30, "Not Applicable");
    }
    else if (discountTypeLookup == 1) {
        strcpy_s(discount, 30, "before Tax");
    }
    else if (discountTypeLookup == 2) {
        strcpy_s(discount, 30, "After Tax");
    }
    else if (discountTypeLookup == 3) {
        strcpy_s(discount, 30, "Before Tax > 14,500");
    }
    if (payTaxLookup == 0) {
        strcpy_s(tax, 30, "No");
    }
    else if (payTaxLookup == 1) {
        strcpy_s(tax, 30, "Yes");
    }
    printf_s("%s %s %f %s %s %s\n", companyId, companyNameLookup, discountRateLookup, discount, tax, pickUpBayLookup);
    return(0);
}

【问题讨论】:

  • 在您的输出中,您可以设置列的宽度,从而保持列的均匀间隔 - 在这里查看参考stackoverflow.com/q/1809399/3858121
  • 有大量的全局变量在使用——这预示着不妙。

标签: c string printf string-formatting


【解决方案1】:

除了Japu_D_Cret提供的link中接受的答案之外,如果您使用%-30s,它会将字符串格式化为30个字符,但如果字符串更长,它将打印所有这些......

试试这个:

printf_s("%s %s %f %-30.30s %-30.30s %s\n", companyId, companyNameLookup, discountRateLookup, discount, tax, pickUpBayLookup);

使用. 意味着它会将字符串格式化为正好30 个字符,- 意味着字符串将左对齐(默认为右对齐)。

编辑:调整代码以反映@Jonathan Leffler 所做的更正

【讨论】:

  • 请注意,%-.30s 的意思是“左对齐;在 30 处截断,除非你早点完成”。如果您希望字段宽度为 30,即使字符串较短,您需要使用%-30.30s。在一般情况下,您可以使用%-*.*s 并为字符串前的每个* 提供相同的int 值——或者,实际上,如果您愿意,您可以为这两个整数使用不同的值,但通常您需要两次相同的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
相关资源
最近更新 更多