如果符合验证要求,我试图将curl查询的内容写入文件。 我的代码编译没有错误但在执行时我收到以下错误 - >
cryptsy # ./foundGetPrice2.o|wgetpaste
foundGetPrice2.o: rapidjson/include/rapidjson/document.h:911: rapidjson::GenericValue<Encoding, Allocator>::MemberIterator rapidjson::GenericValue<Encoding, Allocator>::FindMember(const rapidjson::GenericValue<Encoding, SourceAllocator>&) [with SourceAllocator = rapidjson::MemoryPoolAllocator<>; Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; rapidjson::GenericValue<Encoding, Allocator>::MemberIterator = rapidjson::GenericMemberIterator<false, rapidjson::UTF8<>, rapidjson::MemoryPoolAllocator<> >]: Assertion `IsObject()' failed.
Your paste can be seen here: https://bpaste.net/show/768ea25c86d5
在我的代码的第42行,您可能会注意到curl的2个写行被注释掉了。如果我从那里写write_data(),它可以工作,但没有验证,所以它对我没有好处。
#include "rapidjson/include/rapidjson/document.h"
#include "rapidjson/include/rapidjson/rapidjson.h"
#include "rapidjson/include/rapidjson/writer.h"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <curl/curl.h>
#include <unistd.h>
using namespace rapidjson;
struct myData
{
std::fstream *file;
std::string *str;
};
size_t write_data(void *ptr, size_t size, size_t nmemb, myData *data)
{
size_t numBytes = size * nmemb;
if (data->file)
data->file->write((char*)ptr, numBytes);
if (data->str)
*data->str += std::string((char*)ptr, numBytes);
return numBytes;
}
std::string tradeData;
int getData()
{
int count = 0;
//begin non terminating loop
while(true)
{
count++;
CURL *curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=155");
std::fstream file("myfile.txt", std::ios_base::out | std::ios_base::ate);
std::string json;
myData data;
data.file = &file;
data.str = &json;
//curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
//curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data);
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
else
{
file << std::endl;
Document document;
document.Parse(json.c_str());
std::string tradeUpdate = document["return"]["markets"]["DRK"]["lasttradeprice"].GetString();
if (tradeUpdate > tradeData){
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_data);
std::cout << std::endl;
}
else{
std::cout << "There was an error! " << tradeData << std::endl;
}
}
/* always cleanup */
curl_easy_cleanup(curl);
}
usleep(10000000);
}
return 0;
}
//Le Main
int main(void)
{
getData();
}
gdb输出:
如何在验证后正确写入libcURL请求中的数据?
答案 0 :(得分:0)
由于此行rapidjson
中的断言,程序崩溃了:
std::string tradeUpdate = document["return"]["markets"]["DRK"]["lasttradeprice"].GetString();
实际上,第42行和第43行已注释,您从未向std::string json
分配任何内容,因此它仍然为空,因此document
也是空的。