在C中输出单个字符

Ayd*_*dya 35 c character string-formatting

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

Eva*_*ran 73

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

printf("%c", 'h');
Run Code Online (Sandbox Code Playgroud)

此外,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).
Run Code Online (Sandbox Code Playgroud)

编辑:

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

const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
Run Code Online (Sandbox Code Playgroud)


Roa*_*alt 15

正如其他一个答案中所提到的,您可以使用putc(int c,FILE*stream),putchar(int c)或fputc(int c,FILE*stream)来实现此目的.

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

使用printf就像使用机枪射击一颗子弹一样.

  • `printf()`对于单个字符,就像买一本书得到一张纸. (4认同)

Dou*_*der 14

小心之间的差异'c'"c"

'c' 是一个适合使用%c格式化的char

"c" 是一个char*,指向长度为2的内存块(使用null终止符).

  • 从技术上讲,"c"是一个长度为4(或指针大小不同)的char*,它指向一个内存块,其中包含2个字符('c'和'\ 0').但那只是迂腐. (2认同)