C言語のプログラムで1文字を印刷する場合、フォーマット文字列には必ず"%1s"を使用しなければなりませんか?また、"%c"のように使用することはできますか?
はい、%c
は1つの文字を表示します。
printf("%c", 'h');
また、putchar
/putc
でも動作します。from "man putchar":
#include <stdio.h>
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
EDITです。
また、文字列がある場合、1つの文字を出力するには、出力したい文字列の中の文字を取得する必要があることにも注意してください。例えば、以下のようになります。
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
'c'と
"c"`の違いに注意してください。
'c'
は、%cでのフォーマットに適した文字です。
"c"
は長さ2のメモリブロック(ヌルターミネータ付き)を指すchar*です。