用C语言输出单个字符

在C语言程序中打印单个字符时,我必须在格式字符串中使用"%1s"?我可以使用类似"%c"的东西吗?

是的,%c将打印一个单字符:

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

另外,putchar/putc也可以工作。来自"man putchar":

#include 

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:

还要注意的是,如果你有一个字符串,要输出一个单字符,你需要得到字符串中你想输出的字符。比如说

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
评论(3)

正如其他答案中提到的,你可以使用putc(int c, FILE stream)、putchar(int c)或fputc(int c, FILE stream)达到这个目的。

需要注意的是,使用上述任何一个函数都要比使用任何一个格式解析函数(如printf)快一些,甚至快得多。

使用printf就像用机关枪发射一颗子弹。

评论(1)

注意"'c' "和""c" "之间的区别。

'c'是一个适合用%c格式化的字符。

"c"是一个char*,指向一个长度为2的内存块(带空结尾)。

评论(2)