c - C中输出单个字符

标签 c character string-formatting

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

最佳答案

是的,%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 */

关于c - C中输出单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/310032/

相关文章:

android - 如何使用小数点分隔符正确设置 Double 值的格式?

c - C语言中如何计算crc8?

c - 如何从字符串数组转换为int数组,然后使用c对其进行排序

c - 来自 C 守护进程的 perl 系统调用脚本导致 perl 脚本崩溃

ios - 计算一些字符串 iOS 之前的字符

java - 使用 JCurses 从键盘读取而不按 "enter"

c++ - 在 C++ 中扩展 C 结构

string - 规范包 : how do I combine separate characters?

c# - 仅在 C# 中格式化美分字符串

Python 将撇号写入文件