Reputation: 773
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?
Upvotes: 3
Views: 2302
Reputation: 773
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.
Upvotes: 6