Formatting differences between sprintf() and wsprintf() in VS2015

你说的曾经没有我的故事 提交于 2020-02-06 07:43:30

问题


I am moving some code from multibyte to unicode, and finding my string formatting coming out wrong. It looks like Visual Studio 2015 handles the width argument specifier '*' differently between sprintf() and wsprintf(). Is this a compiler bug or side-effect, or am I missing something really obvious?

Code below, with output:

char    cOutA [ 64 ];
wchar_t wcOutA [ 64 ];

sprintf ( cOutA, "Multibyte = %.*f\n", 3, 2.12345 );
wsprintf ( wcOutA, L"Unicode = %.*f\n", 3, 2.12345 );

printf ( cOutA );
wprintf ( wcOutA );

Output:

Multibyte = 2.123
Unicode = *f

I was expecting both to give me a floating point number to 3 decimal places. What am I doing wrong?


回答1:


As mentioned by Hans in the comments, the answer is you should never use wsprintf(). It's always been broken, does not support the same formatting arguments as C standard "swprintf()" and the Microsoft documentation does not make clear how it is broken or why.

I only discovered this when trying to debug a related function: wvsprintf(). This function seems to have the same limitations, and should also be replaced by its working replacement: "vswprintf()". The similarity of the names to the working versions is very unfortunate, as is the apparent closeness to standard C library functions and naming methodologies. I have no idea why these functions are still delivered in 2017, nor why the Microsoft compiler does not generate a warning when used with unsupported arguments in the same way it does for "sprintf()".

I'm posting this for visibility as searching for these functions on Google doesn't seem to make these massive flaws obvious.



来源:https://stackoverflow.com/questions/46824633/formatting-differences-between-sprintf-and-wsprintf-in-vs2015

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!