Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "encoding error" in the vsnprintf documentation?

Tags:

c++

printf

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?

like image 937
Peeter Joot Avatar asked Oct 19 '25 13:10

Peeter Joot


2 Answers

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.

like image 154
Millie Smith Avatar answered Oct 22 '25 03:10

Millie Smith


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.

like image 41
zkutch Avatar answered Oct 22 '25 03:10

zkutch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!