C++ Format

场景:

1.  C语言有自己的sprintf函数,但是这个函数有个缺点,就是不知道需要创建多大的buffer, 这时候可以使用snprintf函数来计算大小,只要参数 buffer为NULL, count为0即可.

2.  这里实现std::string自己的sprintf也是用了snprintf的特性,先计算大小,再创建空间,之后存入std::string.

3.  还使用了C的可变参数特性.

 

 

[cpp] view plaincopyprint?

  1. std::wstring Format(const wchar_t *format,...)  
  2. {  
  3.     va_list argptr;  
  4.     va_start(argptr, format);  
  5.     int count = _vsnwprintf(NULL,0,format,argptr);  
  6.     va_end(argptr);  
  7.   
  8.     va_start(argptr, format);  
  9.     wchar_t* buf = (wchar_t*)malloc(count*sizeof(wchar_t));  
  10.     _vsnwprintf(buf,count,format,argptr);  
  11.     va_end(argptr);  
  12.       
  13.     std::wstring str(buf,count);  
  14.     free(buf);  
  15.     return str;  
  16. }  


让我们看看可变参数的声明:

 

 

[cpp] view plaincopyprint?

  1. typedef char *  va_list;  

 

[cpp] view plaincopyprint?

  1. #define _INTSIZEOF(n)   ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) )  
  2.   
  3. #define _crt_va_start(ap,v)  ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) )  
  4. #define _crt_va_arg(ap,t)    ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )  
  5. #define _crt_va_end(ap)      ( ap = (va_list)0 )  


注意: ap会累加,每次调用va_arg都会指向下一个参数,问题就是va_arg并不知道什么时候结束,所以如果设计其他的可变参数的函数,要先传入一个参数个数作为方法参数.

 

snprintf 源码实现是通过计算%的个数来判断参数个数的.

 

参考:

http://blog.csdn.net/echoisland/article/details/6086406

https://msdn.microsoft.com/en-us/library/1kt27hek.aspx

https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx

 

[plain] view plaincopyprint?

  1. If buffer is a null pointer and count is zero, len is returned as the count of characters required to format the output, not including the terminating null.   
  2. To make a successful call with the same argument and locale parameters, allocate a buffer holding at least len + 1 characters.  

转载于:https://my.oschina.net/u/4000302/blog/3048497

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值