首先抱歉我的英语不好。 我已经完成了研究,但没有任何相关答案可以解决我的问题。 我已经理解并学习了 CodePages Utf 8 和其他关于 c 或 c++ 的东西, 并且还知道字符串可以容纳 utf8。 我的开发机器 winxp english,控制台代码页设置为 1254(windows 土耳其语),我可以在 std::string 中使用土耳其语扩展字符 (İığşçüö),计算它们并将它们发送到 mysqlpp api 以编写 dbs。没有问题。但是当我想使用 curl 获取一些 html 并将其写入 std::string 时,我的问题就开始了。
#include <iostream>
#include <windows.h>
#include <wincon.h>
#include <curl.h>
#include <string>
int main()
{
SetConsoleCP(1254);
SetConsoleOutputCP(1254);
std::string s;
std::cin>>s;
std::cout<<s<<std::endl;
return 0;
}
当我运行这些程序并输入 ğşçöüİı 时,输出是相同的 ğşçöüİı;
#include <iostream>
#include <windows.h>
#include <wincon.h>
#include <curl.h>
#include <string.h>
size_t writer(char *data, size_t size, size_t nmemb, std::string *buffer);
{
int res;
if(buffer!=NULL)
{
buffer->append(data,size*nmemb);
res=size*nmemb;
}
return res;
}
int main()
{
SetConsoleOutputCP(1254);
std::string html;
CURL *curl;
CURLcode result;
curl=curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://site.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &html);
result=curl_easy_perform(curl);
if(result==CURLE_OK)
{
std::cout<<html<<std::endl;
}
}
return 0;
}
当我编译运行时;
如果 html 包含 'ı' 打印出到 cmd 'ı','ö' 打印出 'Ķ','ğ' 打印出 'ÄŸ','İ' 打印出 'Ä˚' 等等。
如果我将代码页更改为 65000,
...
SetConsoleOutputCP(65000);//For utf8
...
那么结果是一样的,所以问题的原因不是 cmd CodePage。
响应 http headers 表示 charset 设置为 utf-8 并且 html 元数据相同。
据我了解,问题的根源在于函数“writer”或“curl”本身。传入的数据解析为字符,因此将 ı、İ、ğ 等扩展字符解析为 2 个字符,并以这种方式写入 char 数组 std::string,因此相当于打印出这些半个字符的代码页或在代码中的任何地方使用(例如 mysqlpp 以写入该字符串到 db)。
我不知道如何解决这个问题或在 writer 功能或其他任何地方做什么。 我的想法对吗?如果是这样,我该怎么做才能解决这个问题?还是问题的根源在其他地方?
我正在使用 mingw32 Windows Xp 32 位 Code::Blocks ide。
最佳答案
UTF-8 的正确代码页是 65001 , 而不是 65000。
还有,你有没有检查设置代码页是否成功? SetConsoleOutputCP
函数通过其返回值指示成功或失败。
关于c++ - 为什么字符变得无用? libcurl c++ Utf-8 编码的 html;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8286616/