翻译演示无法翻译中文,也许编码失败?

时间:2014-01-17 07:27:31

标签: c++

最近,我实施了一个在线翻译演示,是的,当试图将英文单词翻译成中文时,它运作良好,但不幸的是,它未能将中文单词翻译成英文。

我想也许这个问题是由中文编码引起的,我试图打印网址,然后将它们复制到IE,IE返回的结果是对的。

代码如下:

/*
Filename: translate.cc
Author: BerlinSun
*/
#include <iostream>
#include "curl/curl.h"
#include "json/json.h"

using namespace std;

void usage()
{
    cout << "Usage: translate word_you_want_to_translate" << endl;
}

int writer(char *data, size_t size, size_t nmemb, string *writerData)
{
    if (writerData == NULL)
        return 0;
    int len = size*nmemb;
    writerData->append(data, len); 
    return len;
}

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        usage();
        exit(0);
    }
    string buffer;
    string translate_url = "http://fanyi.youdao.com/openapi.do?keyfrom=xxxxxx&key=xxxxxx&type=data&doctype=json&version=1.1&q=";
    translate_url += argv[1];
    CURL * curl;
    CURLcode res;
    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, translate_url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    if (buffer.empty())
    {
        cout << "The server return NULL!" << endl;
        exit(0);
    }

    Json::Value root;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse(buffer, root);

    if (!parsingSuccessful)
    {
        cout << "Failed to parse the data!" << endl;
        exit(0);
    }

    const Json::Value basic = root["basic"];
    const Json::Value phonetic = basic["phonetic"];
    const Json::Value explains = basic["explains"];
    cout << "Provided by Youdao dictionary!" << endl;
    cout << "-----------------------------" << endl;
    cout << argv[1] << "\t英[" << phonetic.asString()  << "]" << endl;

    for(int i = 0; i < explains.size(); ++i)
        cout << explains[i].asString() << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:0)

这个问题已经由我自己解决了,我检查了libcurl的manaul,发现这是一个可以用来编码url的函数:

char *curl_easy_escape( CURL * curl , char * url , int length );

我修改了我的源来判断argv [1],如果argv [1]是非assic,那么我会用这个函数转换。

谢谢你们。