2016-02-11 8 views
5

特定の文字定数の数値(ifステートメントの数値)を表示するプログラムを作成しようとしています。 1つの問題を除いて、コードは機能します。出力は列内でうまく整列されているはずですが、以下に示すように出力は正しくありません。列を適切に整列させる最善の方法は何ですか?ここでC出力の列の整列

は私のコードです:

#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

+5

ここでの良い解決方法は、書式文字列の文字列整列/長さオプションです。あなたはタブを使って正しい軌道に乗っていますが、説明欄の長さが変わっているのであなたを捨ててしまいます。 'printf("% - 30s "、description)を開始点として試してみてください。 –

+0

コードがうまくいけばhttp://codereview.stackexchange.com/より適しています –

+1

列が並んでいるが、ギザギザになっているので動作しません –

答えて

4

\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のフォーマット文字列に変更:

#平均が、
  • %#03x上記で示唆したように%20.20sを使用
    • それはあなたのために0xの前に付加されます
    • (unsigned char)code最後の1つは、負の文字を渡した場合にうまく動作することを意味します(通常、charsの値の範囲は-128から127です)。
  • +0

    '%#03x'部分を説明できますかより明確に、thx。 –

    +1

    @EricWangそれは '%03x'と似ていますが、開始時に' 0x'を入れます –

    +0

    私はとても素敵な答えを見ています。 –