c(++)可变参数之格式化字符串


 

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 配对使用。

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM