sprintf中的奇怪符号

时间:2012-12-20 13:00:55

标签: c

我在C代码中有以下定义:

#define set_str(r,s) sprintf(r, "%-.*s", (int)sizeof(r)-1,s)

我尝试在我的代码中调用函数set_str来理解符号的含义,但它没有给出任何特殊的格式或任何东西,变量只是按原样复制。谁能告诉我这是什么意思?

3 个答案:

答案 0 :(得分:5)

它只是格式化的输出和一些字符。

% - >表示%之后的字符是占位符,并将被相应的参数替换。

But here few things came into picture that's why you are confused.

. - >完全*表示占用sizeof(r)-1空间

* - >这将指定要打印的字符的大小或宽度,*将替换为sizeof(r)-1

- - >用于左调整或对齐。

上次s - >将由s替换为字符串。

同样sprintf()表示打印到缓冲区。在这种情况下,它是r

编辑:如果是.,请参阅此常规打印方案。

printf("%sx.yz",args); 
// just forget about the `args` it can be as many as the format specifiers,
// it's an example for one argument.

s = sign, can be `+` or `-`.`+` means right adjustment `-`means left adjustment. 
x = At least `x` characters wide.
y = Exactly `y` charactes wide.
z = format specifier like `s`,`d`,`f` and so on as for corresponding arguments. `

答案 1 :(得分:2)

sizeof(r) -1中指定宽度sprintf()的想法是确保目标缓冲区不会溢出。

r是指针时,这不起作用,因为sizeof(char*)不会给出为其分配的字符大小。

例如,如果r分配如下,则上述宏将无法正常工作。

char *r = malloc(50);

答案 2 :(得分:0)

-用于LEFT调整,因为@Omkant说,.表示小数点和下面的帖子会更好地描述* ..

What does the %*s format specifier mean?

相关问题