簡體   English   中英

將可變數量的參數傳遞給別名函數

[英]Pass a variable number of arguments to an aliased function

像printf這樣的函數接受可變數量的參數,我想做的就是將這些可變數量的函數傳遞給子函數而不改變它們的順序。 例如,將printf函數別名為一個稱為console的函數。

#include <stdio.h>

void console(const char *_sFormat, ...);

int main () {
    console("Hello World!");
    return 0;
}

void console(const char *_sFormat, ...) {
    printf("[APP] %s\n", _sFormat);
}

例如,如果我做了console("Hello %s", sName) ,我希望將名稱也傳遞給printf函數,但是它必須能夠像printf一樣繼續接受大量的參數。 。

這就是您想要的:

#include <stdio.h>
#include <stdarg.h>

void console(const char *_sFormat, ...);

int main () {
    console("Hello World!");
    return 0;
}

void console(const char *_sFormat, ...) {
    va_list ap;
    va_start(ap, _sFormat);
    printf("[APP] ");
    vprintf(_sFormat, ap);
    printf("\n");
    va_end(ap);
}

會有另一個問題(由gf指出)-您可能應該將printf_sFormat參數中的字符串連接_sFormat -我懷疑printf是否是遞歸的-因此不會讀取第一個參數中的format語句!

因此,也許這樣的解決方案會更好:

#include <stdarg.h>

void console(const char *_sFormat, ...)
{
  char buffer[256];

  va_list args;
  va_start (args, _sFormat);
  vsprintf (buffer,_sFormat, args);
  va_end (args);

  printf("[APP] %s\n", buffer);
}

使用的類型/功能:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM