对齐C输出中的列

时间:2016-02-11 01:26:08

标签: 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

1 个答案:

答案 0 :(得分:6)

使用\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)。