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