windows下std::string怎么读取utf-8字符
时间: 2024-01-22 17:02:21 浏览: 143
utf8与string的相互转换
4星 · 用户满意度95%
在Windows下使用std::string读取UTF-8字符可以使用以下方法:
1. 使用MultiByteToWideChar函数将UTF-8编码转换为Unicode编码。
```c++
#include <Windows.h>
#include <string>
std::string utf8_to_string(const char* utf8_string)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8_string, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
MultiByteToWideChar(CP_UTF8, 0, utf8_string, -1, wstr, len);
std::wstring wstring(wstr);
delete[] wstr;
return std::string(wstring.begin(), wstring.end());
}
```
2. 使用iconv库进行编码转换。
```c++
#include <iconv.h>
#include <string>
std::string utf8_to_string(const char* utf8_string)
{
iconv_t conv = iconv_open("CP932", "UTF-8");
if (conv == (iconv_t)-1) {
// handle error
}
char* inbuf = const_cast<char*>(utf8_string);
size_t inbytesleft = strlen(utf8_string);
size_t outbytesleft = inbytesleft * 2; // assuming worst case
char* outbuf = new char[outbytesleft];
char* inbufp = inbuf;
char* outbufp = outbuf;
iconv(conv, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
std::string result(outbufp, outbuf - outbufp);
delete[] outbuf;
iconv_close(conv);
return result;
}
```
阅读全文