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

查看:137
本文介绍了在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]; (int index = 0; index< receivedBytes; index ++)
{
str [index] = buffer [index];

}

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

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



Thx用于帮助



Tobi

解决方案

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



还要确保#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天全站免登陆