50

C プログラムで 1 文字を出力する場合、書式文字列で "%1s" を使用する必要がありますか? 「%c」のようなものを使用できますか?

4

5 に答える 5

95

はい、%c単一の文字を出力します:

printf("%c", 'h');

また、putchar/putcも機能します。「マン・プチャー」より:

#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).

編集:

また、文字列がある場合、単一の文字を出力するには、出力する文字列内の文字を取得する必要があることに注意してください。例えば:

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
于 2008-11-21T20:15:13.003 に答える
20

と の違いに'c'注意"c"

'c'%c でフォーマットするのに適した文字です

"c"長さ 2 のメモリ ブロックを指す char* です (ヌル ターミネータ付き)。

于 2008-11-21T20:32:59.753 に答える
17

他の回答の 1 つで述べたように、この目的のためにputc (int c, FILE *stream)、putchar (int c)、またはfputc (int c, FILE *stream) を使用できます。

注意すべき重要なことは、上記の関数のいずれかを使用すると、printf などの形式解析関数を使用するよりも大幅に高速になることです。

printf を使用することは、機関銃を使用して 1 発の弾丸を発射するようなものです。

于 2008-11-21T20:28:42.820 に答える
3
char variable = 'x';  // the variable is a char whose value is lowercase x

printf("<%c>", variable); // print it with angle brackets around the character
于 2008-11-21T22:05:26.370 に答える