输出UTF-8字符

现象

将中文字符串赋值给string类型变量, 并将该变量序列化,通过websocket发送给前端。

SetConsoleOutputCP(65001);
std::cout << "console encode type : 65001" << std::endl;
std::cout << "cpp file encode type : 936" << std::endl;
​
std::string info = "中文字符串_test";
std::cout << info << std::endl;

此时控制台输出该变量为乱码:

且前端无法以UTF-8格式解析字符串,导致websocket断开连接:

解决方法

通过编译器选项指定执行字符集

点击“项目--项目属性”打开属性页窗口,点击“配置属性--C/C++--命令行”,在“其他选项”中填写“/execution-c

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`OutputDebugStringA`函数用于向调试器输出调试信息,它受一个ANSI字符串作为参数。如果你希望输出UTF-8字符串,你需要先将UTF-8字符串转换为ANSI字符串,然后再调用`OutputDebugStringA`函数。以下是一个示例代码: ```cpp #include <windows.h> #include <iostream> #include <string> void OutputDebugStringUTF8(const std::string& utf8String) { int length = MultiByteToWideChar(CP_UTF8, 0, utf8String.c_str(), -1, NULL, 0); if (length == 0) { std::cout << "Failed to convert UTF-8 string to wide string." << std::endl; return; } std::wstring wideString(length, L'\0'); MultiByteToWideChar(CP_UTF8, 0, utf8String.c_str(), -1, &wideString[0], length); std::string ansiString(wideString.begin(), wideString.end()); OutputDebugStringA(ansiString.c_str()); } int main() { std::string utf8String = u8"你好,世界!"; OutputDebugStringUTF8(utf8String); return 0; } ``` 在这个示例代码中,我们定义了一个名为`OutputDebugStringUTF8`的函数,用于输出UTF-8字符串到调试器。 首先,我们使用`MultiByteToWideChar`函数将UTF-8字符串转换为宽字符串(UTF-16)。我们首先调用一次`MultiByteToWideChar`函数来获取转换后的宽字符串的长度,然后创建一个足够容纳宽字符串的`std::wstring`对象,并再次调用`MultiByteToWideChar`函数进行实际的转换。 然后,我们将宽字符串转换为ANSI字符串,通过将宽字符串的`begin()`和`end()`迭代器传递给`std::string`的构造函数来实现。 最后,我们调用`OutputDebugStringA`函数来输出ANSI字符串到调试器。 在`main`函数中,我们定义了一个UTF-8字符串`utf8String`,然后调用`OutputDebugStringUTF8`函数将其输出到调试器。 希望这个示例代码可以帮助你使用`OutputDebugStringA`函数输出UTF-8字符串。如果有任何进一步的问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值