50

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

4

5 回答 5

95

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

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

另外,putchar/putc也可以。来自“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).

编辑:

另请注意,如果您有一个字符串,要输出单个字符,您需要获取要输出的字符串中的字符。例如:

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"是一个 char* 指向长度为 2 的内存块(带有空终止符)。

于 2008-11-21T20:32:59.753 回答
17

如其他答案之一所述,您可以为此目的使用putc (int c, FILE *stream)、putchar (int c) 或fputc (int c, FILE *stream)。

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

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

于 2008-11-21T20:28:42.820 回答
4

输出单个字符的最简单方法是简单地使用该putchar函数。毕竟,这是它的唯一目的,它不能做任何其他事情。不能比这更简单了。

于 2018-12-09T23:24:26.577 回答
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 回答