简体   繁体   English

用C输出单个字符

[英]Output single character in C

When printing a single character in a C program, must I use "%1s" in the format string? 在C程序中打印单个字符时,是否必须在格式字符串中使用“%1s”? Can I use something like "%c"? 我可以使用“%c”之类的东西吗?

yes, %c will print a single char: 是的, %c将打印一个字符:

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

also, putchar / putc will work too. 同样, putchar / putc也可以工作。 From "man putchar": 来自“ 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 */

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. 如其他答案之一所述,您可以为此目的使用putc (int c,FILE * stream), putchar (int c)或fputc (int c,FILE * stream)。

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. 需要注意的重要一点是,使用上述任何功能比使用诸如printf之类的任何格式解析功能要快得多。

Using printf is like using a machine gun to fire one bullet. 使用printf就像使用机枪发射一颗子弹。

Be careful of difference between 'c' and "c" 注意'c'"c"之间的区别

'c' is a char suitable for formatting with %c 'c'是适合用%c格式化的字符

"c" is a char* pointing to a memory block with a length of 2 (with the null terminator). "c"是一个char *,指向长度为2(带有空终止符)的存储块。

char variable = 'x';  // the variable is a char whose value is lowercase x

printf("<%c>", variable); // print it with angle brackets around the character

The easiest way to output a single character is to simply use the putchar function. 输出单个字符的最简单方法是简单地使用putchar函数。 After all, that's it's sole purpose and it cannot do anything else. 毕竟,这是唯一的目的,它无法做其他任何事情。 It cannot be simpler than that. 没有比这更简单的了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM