c - 对齐 C 输出中的列

标签 c

我正在尝试编写一个程序来显示某些字符常量(if 语句中的那些)的数值。除了一个问题外,该代码有效。输出应该在列中很好地对齐,但如下所示,事实并非如此。让列正确排列的最佳方法是什么?

这是我的代码:

#include <stdio.h>
#include <ctype.h>

int main() {

    unsigned char c;

    printf("%3s %9s %12s %12s\n", "Char", "Constant", "Description", "Value");

    for(c=0; c<= 127; ++c){

        if (c == '\n') {
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\n","newline","0x", c);

        }else if (c == '\t'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\t","horizontal tab","0x", c);

        }else if (c == '\v'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\v","vertical tab","0x", c);

        }else if (c == '\b'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\b","backspace","0x", c);

        }else if (c == '\r'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\r","carriage return","0x", c);

        }else if (c == '\f'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\f","form feed","0x", c);

        }else if (c == '\\'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\","backslash","0x", c);

        }else if (c == '\''){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\'","single quote","0x", c);

        }else if (c == '\"'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\"","double quote","0x", c);

        }else if (c == '\0'){
            printf("%3d %7s \t%s \t\t%s%03x\n", c,"\\0","null","0x", c);
        }
    }


    return 0;
}

这是输出:

Output

最佳答案

使用 \t 会让您受制于输出设备。相反,您可以为字符串使用最小字段宽度,例如%-20s 将打印至少 20 个字符,并用空格向右填充。

%-20.20s 将截断更长的字符串; %-20s 会将其他所有内容移到右侧。 - 表示左对齐(默认为右对齐)


为避免代码重复,您可以使用辅助函数,例如:

void print_item(char code, char const *abbrev, char const *description)
{
     printf("%3d %7s %20.20s %#03x\n", code, abbrev, description, (unsigned char)code);
}

// ... in your function
if (c == '\n')
     print_item(c, "\\n", "newline");

我修改了printf格式字符串:

  • 按照上面的建议使用 %20.20s
  • %#03x# 表示它将为您添加 0x
  • (unsigned char)code 最后一个意味着如果您传入任何负字符,它将表现良好。(通常字符的值范围从 -128 到 127)。

关于c - 对齐 C 输出中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329208/

相关文章:

C指针类型类型转换

c - GtkCombo 回调中的 gtk_message_dialog

c - 访问地址内保存的地址

c - POSIX C 线程中上下文切换之前当前堆栈指针寄存器的值存储在哪里

c - 一次传递如何包含到运行 perl 脚本的 execvp?

ios - 使用最新的 iOS SDK 编译时,libcurl 在 iOS 9 上崩溃

python - Ctree Specializer 正在使用 for 循环索引进行计算,而不是实际的数组值

c - 是我的 MIPS 编译器疯了,还是我为选择 MIPS 而疯了?

从多个线程调用相同的函数

c - 我应该使用 Halfcomplex2Real 还是 Complex2Complex