gpt4 book ai didi

c - 获取格式化字符串到变量

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:12 24 4
gpt4 key购买 nike

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

例如:

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

我想在 char* 变量中使用 printf() 输出 "this is a message"。这应该很简单,但除了将其写入文件并根据需要多次读取或连接之外,我不会提供其他东西。

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

最佳答案

你想要 sprintf 或者 snprintf:

用法

char str[128];

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

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

文档


为什么snprintf是安全的

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.

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.

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 则不会。

关于c - 获取格式化字符串到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34775168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com