In the C++ online docs for vsnprintf, it is stated
If an encoding error occurs, a negative number is returned.
What does "encoding error" mean in this context, and can an example of such an error be given?
It is referring to string encoding errors as grinch pointed out. We can reproduce a negative return value with this code, because 129 is an invalid wide character in the Japanese (932) code page when calling wctomb
:
int call_vsnprintf(char* buf, int max, char* format, ...)
{
va_list args;
va_start(args, format);
#pragma warning (suppress : 4996)
int result = vsnprintf(buf, max, format, args);
va_end(args);
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, ".932");
char dest[100];
wchar_t wbuf[2];
wbuf[0] = 129;
wbuf[1] = 0;
//this will be -1
int result = call_vsnprintf(dest, sizeof(dest), "%ls", wbuf);
}
Note: This was on Windows, but if it's not portable, it can be fixed easily by searching Asian codepages for widechars that force wctomb to return -1.
Thanks to James Kuyper on Google Groups for pretty much the entire answer.
Let me confirm on Debian Millie Smith answer:
char dest[100];
wchar_t wbuf[2];
wbuf[0] = 129;
wbuf[1] = 0;
int result = snprintf(dest, sizeof(dest), "%ls", wbuf);
result is -1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With