2008-11-21 58 views
32

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

回答

60

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

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

putchar/putc也能工作。从“人的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 */ 
+0

我正在使用MS C 6.0,它不起作用。也没有提供任何错误。 – Aydya 2008-11-21 20:27:57

+0

你可以发布一些非工作示例代码吗?确保在'%c'中'c'是小写字母。 – 2008-11-21 20:30:13

+0

您是否尝试复制并粘贴我的示例。 %c应该工作,因为参数是正确的类型(一个字符,而不是一个字符串)。 – 2008-11-21 20:42:20

14

如在其他的答案中的一个所提到的,可以使用putc将(INT C,FILE *流),的putchar(INT c)或的fputc(INT C,FILE *流)为此目的。

需要注意的是,使用上述任何函数都比使用printf等任何格式解析函数要快得多。

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

10

小心差的'c'"c"

'c'是适合于与%C

"c"被一个char *指向存储块为2的长度格式化炭(与空终止子之间)。

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