3

通常の機能の使用法:

my_func("test");

このパラメーターを使用できるかどうか。

my_func(printf("current_count_%d",ad_id));

int my_func(const char *key)

4

5 に答える 5

8

はい、の戻り値をprintf関数パラメーターとして使用できます。ただし、成功すると、書き込まれた文字数が返されることを
忘れないでください。それでprintf

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

関数に渡さ6れません。foobar123

printf印刷する文字列を渡したい場合は、sprintf関数を利用できます。printfこれは、コンソールに書き込む代わりに、char配列に書き込むのと似ていますが。

于 2010-10-26T08:55:44.370 に答える
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)
于 2010-10-26T09:03:04.287 に答える
2

printfが受け入れるような可変数の引数を関数に渡す場合は、を調べる必要があります。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に渡され、「可変引数はこの引数の後に開始されます」と表示されます。

于 2010-10-26T09:22:06.480 に答える
2

いいえ; printf()stdout に出力された文字数を返します。を使用s[n]printf()して文字列を作成し、それを渡します。

于 2010-10-26T08:54:13.847 に答える
1

この関数printf は整数を返します

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

したがって、パラメータとして整数を取るmy_func限り、それを使用できます。my_funcこれは当てはまらないようです。

于 2010-10-26T08:55:22.763 に答える