日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

[C/C++标准库]_[0基础]_[怎样实现std::string自己的Format(sprintf)函数]

發布時間:2025/3/17 c/c++ 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [C/C++标准库]_[0基础]_[怎样实现std::string自己的Format(sprintf)函数] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.


場景:

1.? C語言有自己的sprintf函數,可是這個函數有個缺點,就是不知道須要創建多大的buffer, 這時候能夠使用snprintf函數來計算大小,僅僅要參數 buffer為NULL, count為0就可以.

2.? 這里實現std::string自己的sprintf也是用了snprintf的特性,先計算大小,再創建空間,之后存入std::string.

3.? 還使用了C的可變參數特性.


std::wstring Format(const wchar_t *format,...) {va_list argptr;va_start(argptr, format);int count = _vsnwprintf(NULL,0,format,argptr);va_end(argptr);va_start(argptr, format);wchar_t* buf = (wchar_t*)malloc(count*sizeof(wchar_t));_vsnwprintf(buf,count,format,argptr);va_end(argptr);std::wstring str(buf,count);free(buf);return str; }
讓我們看看可變參數的聲明:

typedef char * va_list;
#define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) )#define _crt_va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) ) #define _crt_va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) ) #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

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. To make a successful call with the same argument and locale parameters, allocate a buffer holding at least len + 1 characters.

轉載于:https://www.cnblogs.com/yutingliuyl/p/6758546.html

總結

以上是生活随笔為你收集整理的[C/C++标准库]_[0基础]_[怎样实现std::string自己的Format(sprintf)函数]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。