在c ++中获取正确编码的字符串 [英] Get Strings in right encoding in c++

查看:162
本文介绍了在c ++中获取正确编码的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前问过一个类似的问题。
但是我仍然在c ++编码的麻烦。
我尝试尽可能描述问题。



我有一个c ++客户端,通过TCP与c#服务通信。
现在我需要在Messagebox(Win32 API)中显示来自服务的消息。
C#服务发送的字节是UTF-8编码的。



重要的是,c ++客户端只能在Windows系统上运行。 p>

这是接收字节并显示文本的代码:

  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);

如果文本包含üäö之类的聊天字符,则它们不会以正确的方式显示在Messagebox中。
我可以做什么来接收消息为UTF-8字符串在c ++?
是否有可能将char []转换为UTF-8字符串?



Thx帮助


$ b b

Tobi

解决方案

如果要在Windows中显示unicode字符,需要将UTF8字符串转换为UTF16 UCS2),因为这是unicode标准的Windows句柄。您可以使用 MultiByteToWideChar 功能。 / p>

还要确保#define UNICODE在包含Windows标题之前设置,以便MessageBox指向MessageBoxW或显式使用MessageBoxW。


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

解决方案

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.

这篇关于在c ++中获取正确编码的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆