函数参数中的printf函数

3
通常函数的用法:
my_func("test");

我能使用这个参数吗?
my_func(printf("current_count_%d",ad_id));

int my_func(const char *key)


请说明您想要实现什么。my_func的意图是什么? - Keynslug
sprintf当然是可以用的... int my_func(const char *key) - Bdfy
5个回答

8

是的,您可以将printf的返回值用作函数参数。
但请记住,printf成功时返回写入的字符数。
因此

foo(printf("bar%d",123)); 

函数将6作为参数传递给foo,而不是bar123

如果您想传递printf打印的字符串,可以使用sprintf函数。它类似于printf,但不是写入控制台,而是写入到字符数组中。


4
    char buf[64]; /* malloc or whatever */
    int pos = snprintf(buf, sizeof(buf), "current_count_%d", ad_id);
    if (sizeof(buf) <= pos)
                    buf[sizeof(buf)-1] = '\0';
    my_func(buf)

经过快速的研究,只有在Windows系统上,如果snprintf截断输出,则无法添加终止NULL。因此,如果这是Microsoft对C89后续发展不感兴趣的一个错误或副作用,我并不感到惊讶。 - Tommy

2
如果您想要传递可变数量的参数,例如printf函数接受的参数,那么您需要查看“va_arg”功能。为了举例说明如何复制printf函数:
void varargfunc(char *fmt, ...)
{
    char formattedString[2048]; /* fixed length, for a simple example - and
                                   snprintf will keep us safe anyway */
    va_list arguments;

    va_start(arguments, fmt); /* use the parameter before the ellipsis as
                                 a seed */

    /* assuming the first argument after fmt is known to be an integer,
       you could... */
    /*
        int firstArgument = va_arg(arguments, int);
        fprintf(stderr, "first argument was %d", firstArgument);
    */

    /* do an vsnprintf to get the formatted string with the variable
       argument list. The v[printf/sprintf/snprintf/etc] functions
       differ from [printf/sprintf/snprintf/etc] by taking a va_list
       rather than ... - a va_list can't turn back into a ... because
       it doesn't inherently know how many additional arguments it
       represents (amongst other reasons) */
    vsnprintf(formattedString, 2048, fmt, arguments);

    /* formattedString now contains the first 2048 characters of the
       output string, with correct field formatting and a terminating
       NULL, even if the real string would be more than 2047 characters
       long. So put that on stdout. puts adds an additional terminating
       newline character, so this varies a little from printf in that 
       regard. */
    puts(formattedString);

    va_end(arguments); /* clean up */
}

如果您想添加与格式无关的其他参数,请将它们添加到“fmt”参数之前。Fmt被传递给va_start,以表示“变量参数从此后开始”。

2

不,printf()返回打印到标准输出的字符数。使用s[n]printf()创建字符串,然后传递该字符串。


请记住,您将需要手动声明一个 char[] buffer 并在使用完毕后释放它。 - Christian Mann
或者只需使用静态声明长度的数组,例如char buffer[50]或其他。 - Tommy
没错,因为它们是原始类型,而不是对象。我的错误。 - Christian Mann

1

printf函数返回一个整数

int printf ( const char * format, ... );

因此,只要my_func接受整数作为参数,就可以在my_func中使用它。但事实似乎并非如此。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接