1. はじめに
printf関数では、表示の右詰めなど整形をすることができる。
まずは、普通にprintf関数を使用して、数値を表示する。
#include <stdio.h>
int main() {
printf("%d\n", 1);
printf("%d\n", 10);
printf("%d\n", 100);
printf("%d\n", 1000);
printf("%d\n", 10000);
return 0;
}
出力は以下になる。
これを様々な形に整形する。
1
10
100
1000
10000
2. 右詰めにする
出力を右詰めにするには、%のあとに、空白埋めたい幅数を記述する。
#include <stdio.h>
int main() {
printf("%5d\n", 1);
printf("%5d\n", 10);
printf("%5d\n", 100);
printf("%5d\n", 1000);
printf("%5d\n", 10000);
return 0;
}
1
10
100
1000
10000
3. 左をゼロ埋めにする
左をゼロ埋めにするには、%のあとに 0 を記述し、その後にゼロ埋めしたい幅数を記述する。
#include <stdio.h>
int main() {
printf("%05d\n", 1);
printf("%05d\n", 10);
printf("%05d\n", 100);
printf("%05d\n", 1000);
printf("%05d\n", 10000);
return 0;
}
00001
00010
00100
01000
10000
4. フィールド境界で左詰めする
フィールド境界で左詰めにするには、%のあとに - を記述し、その後に空白埋めしたい幅数を記述する。
#include <stdio.h>
int main() {
printf("[%-5d]\n", 1);
printf("[%-5d]\n", 10);
printf("[%-5d]\n", 100);
printf("[%-5d]\n", 1000);
printf("[%-5d]\n", 10000);
return 0;
}
[1 ]
[10 ]
[100 ]
[1000 ]
[10000]
5. 正の時に+記号を付加する
デフォルトでは、負の値の時には-記号が付きるが、正の値の時には何もつかない。
正の値の時にも+記号を付けたい場合は、%のあとに+を記述する。
#include <stdio.h>
int main() {
printf("%+d\n", 1);
printf("%+d\n", -1);
return 0;
}
+1
-1
0件のコメント