c - %.s 的 sprintf 用法

标签 c printf

像这样使用 sprintf 时

sprintf("%.40s",str);

我想给出一个类似 strlen(str) 的值来代替 40。我该怎么做?我尝试用 strlen(str) 替换 40,但没有用。给一个值,比如

#define len strlen(str)

并且使用 %.len 也不起作用,因为 %.len 用于“”。

最佳答案

使用*字符。

sprintf(/* ... */, "%.*s", (int) strlen(str), str);

如果你使用C99,snprintf也可以适用。

man printf (3)
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

关于c - %.s 的 sprintf 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13289315/

相关文章:

c - while (scanf()==1) 不起作用 - 我的错误是什么?

c++ - sprintf 的内部工作

c - 使用 printf ("%s",&Buffer[i]);在C中

c - C 中的 const 修饰符

C : assign value to uninitialzed struct and union

c - 如何在该 MIPS 代码的基本数组中存储偏移量?

c - 打印 CString 会打印之前未知的文本

c - 如何确定我的系统上 malloc() 结果的最小对齐?

java - 如何在 StdOut.printf (JAVA) 中使用整数 n

linux - 在汇编中使用 printf 会导致管道输出为空,但在终端上有效