将格式化字符串转换为变量 [英] get formatted string to a variable

查看:80
本文介绍了将格式化字符串转换为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何 C 函数(或一种方法)可以将格式化字符串作为普通字符串获取?

Is there any C function (or a way) to get a formatted string as a normal string?

例如:

printf("this is %s", "a message")

我想要 printf() 的输出 "this is a message"char* 变量中.这应该很简单,但除了将其写入文件并根据需要多次读取或连接之外,我不会带来任何东西.

I want printf()s output "this is a message" in a char* variable. This should be simple but I'm not coming with something besides write it to a file and read it or concatenate as many times as needed.

那么,有没有一种函数或一种简单的方法可以将任何格式化的字符串放入 C 中的单个字符串变量中?

So, is there a function or an easy way to put any formatted string into a single string variable in C?

推荐答案

你想要 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.

这篇关于将格式化字符串转换为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆