且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将格式化字符串转换为变量

更新时间:2023-11-15 18:15:04

你想要 sprintf 或者 snprintf:

char str[128];

//sprintf(str, "hello %s", "world");
snprintf(str, 128, "hello %s",  "world");

请注意,snprintf 更安全,因为它会将字符串切割为遇到溢出的适当长度.

Note that snprintf is safer since it will cut the string to appropriate length of encountered overflow.

snprintf 将输出写入字符串 str,在格式字符串 format 的控制下,指定如何转换后续参数以供输出.它类似于 sprintf(3),不同之处在于 size 指定要生成的最大字符数.尾随的 nul 字符计入此限制,因此您必须至少为 str 分配 size 个字符.

snprintf writes output to the string str, under control of the format string format, that specifies how subsequent arguments are converted for output. It is similar to sprintf(3), except that size specifies the maximum number of characters to produce. The trailing nul character is counted towards this limit, so you must allocate at least size characters for str.

如果 size 为零,则不写入任何内容并且 str 可能为空.否则,超出 n-1st 的输出字符将被丢弃而不是写入 str,并在实际写入 的字符末尾写入一个 nul 字符>str.如果复制发生在重叠的对象之间,则行为未定义.

If size is zero, nothing is written and str may be null. Otherwise, output characters beyond the n-1st are discarded rather than being written to str, and a nul character is written at the end of the characters actually written to str. If copying takes place between objects that overlap, the behaviour is undefined.

成功时,返回在 size 足够大的情况下会写入的字符数,不包括终止的 nul 字符.因此,当且仅当返回值为非负且小于 size 时,才完全写入以 null 结尾的输出.出错时,返回 -1(即编码错误).

On success, returns the number of characters that would have been written had size been sufficiently large, not counting the terminating nul character. Thus, the nul-terminated output has been completely written if and only if the return value is nonnegative and less than size. On error, returns -1 (i.e. encoding error).

也就是说,snprintf 可以保护程序员免受缓冲区溢出的影响,而 sprintf 则不会.

That is, snprintf protects programmers from buffer overruns, while sprintf doesn't.