对齐C输出中的列

Tuc*_*amp 6 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;
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

产量

M.M*_*M.M 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");
Run Code Online (Sandbox Code Playgroud)

我修改了printf格式字符串:

  • 使用%20.20s如上所述
  • %#03x,#它将0x为你提供的手段
  • (unsigned char)code 对于最后一个意味着如果你传递任何负的字符,它将表现得很好.(通常字符的值范围从-128到127).