[英]C++ Printf Style Formatting for Std::String
I was writing a utility function to do sprintf like formatting for std::string or std::wstring based on Unicode settings. 我正在编写一个实用程序函数来执行sprintf之类的操作,例如基于Unicode设置对std :: string或std :: wstring进行格式化。
#ifdef _UNICODE
typedef std::wstring MyString ;
typedef TCHAR MyChar ;
#define MYTEXT TEXT
#else
typedef std::string MyString ;
typedef char MyChar ;
#define MYTEXT
#endif //_UNICODE
MyString Utils::GetStringPrintf(const MyString kstrText, ...)
{
int iCharsWritten = 0 ;
MyString strFinal ;
MyChar szBufferTouse[8194] ; //Hopefully Long enough
va_list fmtList ;
va_start(fmtList, kstrText) ;
/*int iVal = va_arg(fmtList, int) ;*/ =>Just for debugging
#ifdef _UNICODE
iCharsWritten = _stprintf_s(szBufferTouse, 8194, kstrText.c_str(), fmtList) ;
#else
iCharsWritten = sprintf_s(szBufferTouse, 8194, kstrText.c_str(), fmtList) ;
#endif //_UNICODE
va_end(fmtList) ;
strFinal = szBufferTouse ;
return strFinal ;
}
When called like : 当被称为:
int iId = 2 ;
MyString strFileName = Utils::GetStringPrintf(MYTEXT("Student_%d.png"), iId) ;
//For Unicode am getting Student_1633600.png instead of Student_2.png //For non-Unicode am getting Student_1633800.png instead of Student_2.png //对于Unicode,获取的是Student_1633600.png而不是Student_2.png;对于非Unicode,获取的是Student_1633800.png,而不是Student_2.png
Upon debugging I do get the value of iVal as 2, but somehow the values get bad upon passing to sprintf. 调试后,我确实将iVal的值设为2,但是以某种方式传递给sprintf时,这些值变得不好。
However if I call, sprintf directly, 但是,如果我直接打电话给sprintf,
MyChar szFilename[200] ;
int iId = 2 ;
_stprintf_s(szFilename, 200, MYTEXT("Student_%d.png"), iId) ;
Am getting proper output, ie Student_2.png 正在获得正确的输出,即Student_2.png
I did refer other posts in Stack Overflow regarding sprintf functionality and found my code to be doing quite similar to those. 我确实参考了Stack Overflow中有关sprintf功能的其他文章,发现我的代码与这些代码非常相似。 Is there any problem in passing va_list repeatedly to functions. 将va_list重复传递给函数是否有任何问题。
Replace sprintf_s
with vsprintf
(and remove size) or with vsprintf_s
if available. 更换sprintf_s
与vsprintf
(和删除大小)或vsprintf_s
(如果可用)。
Quoting from manpage of printf. 引用printf的联机帮助页。 (Emphasis mine) (强调我的)
The functions vprintf(), vfprintf(), vsprintf(), vsnprintf() are equivalent to the functions printf(), fprintf(), sprintf(), snprintf() , respectively, except that they are called with a va_list instead of a variable number of arguments . 函数vprintf(),vfprintf(),vsprintf(),vsnprintf()分别等效于函数printf(),fprintf(),sprintf(),snprintf() ,不同之处在于它们使用va_list而不是va_list进行调用可变数量的参数 。 These functions do not call the va_end macro. 这些函数不调用va_end宏。 Because they invoke the va_arg macro, the value of ap is undefined after the call. 由于它们调用va_arg宏,因此在调用之后ap的值是不确定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.