3

I asked a similar question before. But I am still in trouble with encodings in c++. I try to describe the problem as well as possible.

I have a c++ client, communicating with an c# service over TCP. Now I need to display the Messages from the service in an Messagebox (Win32 API). The Bytes, sended by the c# service are UTF-8 encoded.

Important to know, the c++ client will only be running on Windows Systems.

This is the code to receive the bytes and to display the Text:

    char buffer[1024];
    int receivedBytes = recv(socketHandle, buffer, sizeof(buffer) - 1, 0);
    char str[receivedBytes];
    for (int index = 0; index < receivedBytes; index++)
    {
        str[index] = buffer[index];
    }

    MessageBox(mainWindow, (LPCTSTR)str, (LPCTSTR) "Fehler", MB_OK|MB_ICONERROR);

If the Text contains chatacters like üäö, they are not shown in the Messagebox the correct way. What can I do to receive the message as UTF-8 String in c++? Is there a possibility to convert the char[] to an UTF-8 String?

Thx for helping

Tobi

5
  • 2
    there are really two questions there: how do I handle utf8 string in tcp connections? and how do I handle utf8 string with winapi? Commented Apr 12, 2013 at 8:09
  • 3
    Maybe because you don't seem to set result anywhere? Commented Apr 12, 2013 at 8:09
  • 1
    maybe this question would help : stackoverflow.com/questions/504779/winapi-and-utf-8-support Commented Apr 12, 2013 at 8:12
  • What is the point of copying buffer to str? It's sufficient if you just add a terminating 0 at the receivedBytes index, as in buffer[receivedBytes] = 0;. Apart from that, it's better to use memcpy for that purpose than copy byte by byte in a loop. Commented Apr 12, 2013 at 8:30
  • Sorry, that should not be result, but this is not the problem. Commented Apr 12, 2013 at 8:31

1 Answer 1

7

If you want to display unicode characters in Windows, you need to translate UTF8 string into UTF16 (older UCS2), as this is the unicode standard Windows handles. You do that with MultiByteToWideChar function.

Also make sure that the #define UNICODE is set before you include Windows headers, so that MessageBox points to MessageBoxW or use MessageBoxW explicitly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.