c++获取百度翻译API
时间: 2023-11-18 18:43:48 浏览: 80
以下是使用C++获取百度翻译API的代码示例:
```C++
#include <iostream>
#include <curl/curl.h>
#include <json/json.h>
using namespace std;
size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up) {
for (int c = 0; c < size * nmemb; c++) {
((string*)up)->push_back(buf[c]);
}
return size * nmemb;
}
string translate(string q, string from, string to) {
string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?"
"q=" + q +
"&from=" + from +
"&to=" + to +
"&appid=你的APPID" +
"&salt=1" +
"&sign=你的SIGN";
CURL* curl = curl_easy_init();
if (curl) {
string response_string;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
Json::Value root;
Json::Reader reader;
bool parsing_successful = reader.parse(response_string, root);
if (!parsing_successful) {
cerr << "Failed to parse the response data" << endl;
return "";
}
int error_code = root["error_code"].asInt();
if (error_code != 0) {
cerr << "Translation failed with error code " << error_code << endl;
return "";
}
string translation;
const Json::Value translations = root["trans_result"];
for (int i = 0; i < translations.size(); i++) {
translation += translations[i]["dst"].asString();
}
return translation;
}
return "";
}
int main() {
string translation = translate("Hello, world!", "en", "zh");
cout << "Translation: " << translation << endl;
return 0;
}
```
其中,需要替换其中的APPID和SIGN为自己的百度翻译API的APPID和签名。
阅读全文