0、序言
使用printf函數,其參數就是可變參數。下面將使用 C語言 的庫函數實現可變參數的函數 。
用途(歡迎補充):
A、記錄日志,可能需要將變量格式化輸出到日志文件。
B、格式化字符串,顯示結果(A差不多)。
1、使用
A、頭文件
// 使用va_start需要的頭文件 #include <stdarg.h>
B、必須使用下面的3個宏 :
va_list va_start va_end
C、使用函數: snprintf (sprintf的升級版,避免緩沖區溢出)
D、函數范例
void show_str(const char* pstr, ...);
2、一個例子
1 #include <iostream> 2 3 // 使用va_start需要的頭文件 4 #include <stdarg.h> 5 6 void show_str(const char* pstr, ...) 7 { 8 va_list ap; 9 va_start(ap, pstr); 10 11 // 1、計算得到長度 12 //--------------------------------------------------- 13 // 返回 成功寫入的字符個數 14 int count_write = snprintf(NULL, 0, pstr, ap); 15 va_end(ap); 16 17 // 長度為空 18 if (0 >= count_write) 19 return ; 20 21 count_write ++; 22 23 // 2、構造字符串再輸出 24 //--------------------------------------------------- 25 va_start(ap, pstr); 26 27 char *pbuf_out = NULL; 28 pbuf_out = (char *)malloc(count_write); 29 if (NULL == pbuf_out) 30 { 31 va_end(ap); 32 return; 33 } 34 35 // 構造輸出 36 vsnprintf(pbuf_out, count_write, pstr, ap); 37 // 釋放空間 38 va_end(ap); 39 40 // 輸出結果 41 std::cout << "str = " << pbuf_out << "\n"; 42 43 // 釋放內存空間 44 free(pbuf_out); 45 pbuf_out = NULL; 46 } 47 48 49 // 入口函數 50 int main(int argc, char *argv[]) 51 { 52 show_str("123, %s, %s", "ABC", "-=+"); 53 54 system("pause"); 55 return 0; 56 }
show_str函數實現輸出構造好的字符串。
3、結果
演示環境: VS2015 up3
輸出結果:
4、總結
A、注意 ,這里是malloc , 需要與 free 配對使用,避免內存泄漏
B、注意,va_start 需要與 va_end 配對使用。