まぬねこの足跡。。。

備忘録+たのしさ+ひっそりと

C言語 文字・数字の表示

文字列表示

  • 「"」(ダブルクォーテーション)で文字列を囲む

※文字列を文字列リテラルという。

printf("Hello World");

表示イメージ

改行 エスケープシーケンス

  • 「\n」をつける
printf("Hello \n");
printf("World");

表示イメージ

Hello World

数値表示

printf(出力変換指定子, 数値);

printf("%d", 100);

表示イメージ

100

出力変換指定子

<よく使うもの>

指定子 説明
%c char 1文字を出力する
%s char * 文字列を出力する
%d int, short 整数を10進で出力する
%ld long 倍精度整数を10進で出力する
%f float 実数を出力する
%lf double 倍精度実数を出力する

https://manulcat280.hatenablog.com/entry/2023/04/29/出力変換指定子

文字列+数値 表示

printf("%d年です\n", 3000);

表示イメージ

3000年

複数の「文字列+数値」表示

printf("%d%d%d\n", 3000,4, 1);

表示イメージ

3000年4月1日

表示桁数の指定

%全体桁数.小数桁数

printf("[%8.3f]", 123.45678);
printf("[%15s]", "cgenngo");
printf("[%.5s]", "cgenngo");
printf("[%8.3e]", 1234.5678);

表示イメージ
※□:スペース

□□123.456
□□□□□□□□□cgengo
cgenngo
1.234e+3

ゼロ詰め

printf("[%08.3f]", 123.45678);
printf("[%06d]", 1);

表示イメージ

0123.456
000001

左詰め

printf("[%-15s]", "cgenngo□□□□□□□□");
printf("[%-8.3f]", 123.45678);
printf("[%-5d]", 1);

表示イメージ
※□:スペース

cgenngo□□□□□□□□
123.456□□
1□□□□

符号の指定

printf("[%+5d]", 12);
printf("[%+5d]", -12);
printf("[%+8.3f]", 1.234);

表示イメージ
※□:スペース

□□□+12
□□□-12
□□□□+1.234