Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output single character in C

When printing a single character in a C program, must I use "%1s" in the format string? Can I use something like "%c"?

like image 884
Aydya Avatar asked Nov 21 '08 20:11

Aydya


People also ask

What is single character value in c?

C – Read Single Character using Scanf() So, to read a single character from console, give the format and argument to scanf() function as shown in the following code snippet. char ch; scanf("%c", ch); Here, %c is the format to read a single character and this character is stored in variable ch .

How do I print a single character from a string?

printf("%c\n", string[n-1]);

Which is the single character input output function?

The single character input/output functions are Getchar () and putchar (). Getchar() is used to get a single character and require key after input. Putchar() is used to put a single character on the standard output device.


1 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 */ 
like image 197
Evan Teran Avatar answered Sep 20 '22 03:09

Evan Teran