2012-05-13 42 views
0

只是想学习C++。我以刮刀开始。这个想法是我想刮一堆页面,应用正则表达式,并将我的发现写入文件。C++:使用libcurl和流

但是,我目前卡住试图分配curl句柄写入字符串变量。任何指针(我的意思是......)?

#include <stdio.h> 
#include <curl/curl.h> 
#include <string> 
#include <iomanip> 
#include <boost/lexical_cast.hpp> 

// Typedefs 
using std::string;  using boost::lexical_cast; 
using std::cout; 
using std::endl; 
using std::ostringstream; 

// CURL directives 
static const string BASE_URL = "http://www.XXXXXX.com/action?page="; 
static char* USER_AGENT_STRING = "C++ Scraper"; 

// CURL variables 
static CURL* curl; 
static CURLcode res; 

     void setPageOpts(CURL* c, int count, const ostringstream stream) { 
      cout << "Got to the set opts method." << endl; 

      // Set URL 
      string new_url = BASE_URL + lexical_cast<string>(count); 
      curl_easy_setopt(curl, CURLOPT_URL, new_url.c_str()); 
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream); 
     } 

     void setConstOpts(CURL *c) { 
      // User agent string 
      curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT_STRING); 
      //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); 
     } 

     void loadCurl() { 
      int status = curl_global_init(CURL_GLOBAL_ALL); 

      if (status != 0) { 
       cout << "An error has occurred with exit status " << status << endl; 
       exit(status); 
      } 
     } 

     int main() { 
      loadCurl(); 
      curl = curl_easy_init(); 

      if(curl) { 
       setConstOpts(curl); 

       for (int i = 1; i < 2; ++i) {   
        const ostringstream stream; 

        setPageOpts(curl, i, &stream); 

        res = curl_easy_perform(curl); 

        string output = stream.get(); 
        cout << "And the data was: " << endl << endl << output << endl; 
       } 

       curl_easy_cleanup(curl); 
      } 

      // Everything went as planned 
      return 0; 
     } 

当前错误我越来越:

learn.cpp:15: warning: deprecated conversion from string constant to 'char*' 
learn.cpp: In function 'int main()': 
learn.cpp:62: error: conversion from 'const std::ostringstream*' to non-scalar type 'std::ostringstream' requested 
learn.cpp:67: error: request for member 'get' in 'stream', which is of non-class type 'const std::ostringstream*' 

我看到它的方式,我想卷曲流的位置在内存中,以便它可以在里面写。所以我认为我需要使用一个&角色,并将其交给。但这似乎并不奏效。

回答

2

你的定义:

void setPageOpts(CURL* c, int count, const ostringstream stream) 

可能导致您的问题。它看起来像你的意思是通过引用传递在stream,以便它可以被更新:

void setPageOpts(CURL* c, int count, ostringstream& stream) 

(不要忘记使用c当你通过它)。

然后,而不是这样的:

   const ostringstream stream; 
       setPageOpts(curl, i, &stream); 

调用你的函数:

 ostringstream stream; 
     setPageOpts(curl, i, stream); 

这将允许stream进行更新。

std::ostringstream没有::get()。我想你的意思是:

 string output = stream.str(); 

您也可以找到有用的this answer,竟未CURLOPT_WRITEFUNCTION指定要使用你的std::ostringstream指针的回调函数,你会得到一个访问冲突,libcurl何时何地试图write它。

3

的第一个警告是

static char* USER_AGENT_STRING = "C++ Scraper"; 

其中文字是const,所以你指针应是指向const char。第二个问题是const ostringstream stream。如果数据流是const,则无法对其进行任何改变其状态的任何操作,例如读取或写入。