c++ gbkToUtf8
To convert a GBK-encoded string to UTF-8 in C++, you can use the iconv library. Here's an example code snippet:
#include <iostream>
#include <string>
#include <iconv.h>
std::string gbkToUtf8(const std::string& gbkString) {
// Open the conversion descriptor
iconv_t conv = iconv_open("UTF-8", "GBK");
if (conv == (iconv_t)-1) {
std::cerr << "Failed to open conversion descriptor" << std::endl;
return "";
}
// Prepare input and output buffers
const char* inbuf = gbkString.c_str();
size_t inbytesleft = gbkString.length();
char outbuf[1024]; // Adjust buffer size as needed
char* outptr = outbuf;
size_t outbytesleft = sizeof(outbuf);
// Convert GBK to UTF-8
if (iconv(conv, (char**)&inbuf, &inbytesleft, &outptr, &outbytesleft) == (size_t)-1) {
std::cerr << "Conversion failed" << std::endl;
iconv_close(conv);
return "";
}
// Close the conversion descriptor
iconv_close(conv);
// Construct the UTF-8 string
std::string utf8String(outbuf, outptr - outbuf);
return utf8String;
}
int main() {
std::string gbkString = "你好世界"; // Replace with your GBK-encoded string
std::string utf8String = gbkToUtf8(gbkString);
std::cout << "UTF-8 string: " << utf8String << std::endl;
return 0;
}
Make sure to link against the iconv library by adding -liconv to your compilation command
原文地址: https://www.cveoy.top/t/topic/h1ud 著作权归作者所有。请勿转载和采集!