When printing a single character in a C program, must I use "%1s" in the format string? Can I use something like "%c"?
5 Answers
yes, %c
will print a single char:
printf("%c", 'h');
also, putchar
/putc
will work too. From "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).
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */

- 51
- 5

- 87,561
- 32
- 179
- 238
-
I am using MS C 6.0 and it does not work. Gives no error either. – Aydya Nov 21 '08 at 20:27
-
Could you post some non-working sample code? Make sure the 'c' is lowercase in the '%c'. – Adam Rosenfield Nov 21 '08 at 20:30
-
did you try copy and pasting my example. %c should work given that the parameter is of the correct type (a char, not a string). – Evan Teran Nov 21 '08 at 20:42
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).

- 52,368
- 9
- 94
- 137
-
4Technically, "c" is a char* with a length of 4 (or whatever your pointer size is) that points to a block of memory with 2 characters in it ('c' and '\0'). But that's just being pedantic. – paxdiablo Nov 22 '08 at 02:01
As mentioned in one of the other answers, you can use putc(int c, FILE *stream), putchar(int c) or fputc(int c, FILE *stream) for this purpose.
What's important to note is that using any of the above functions is from some to signicantly faster than using any of the format-parsing functions like printf.
Using printf is like using a machine gun to fire one bullet.

- 8,330
- 7
- 41
- 53
-
7`printf()` for single char, is like buying a book to get a piece of paper. – exebook Nov 08 '13 at 03:58
The easiest way to output a single character is to simply use the putchar
function. After all, that's it's sole purpose and it cannot do anything else. It cannot be simpler than that.

- 30,332
- 17
- 55
- 95
char variable = 'x'; // the variable is a char whose value is lowercase x
printf("<%c>", variable); // print it with angle brackets around the character

- 28,120
- 21
- 85
- 141