CMouse
CMouse

Reputation: 130

Convert std::string to boost::asio::streambuf

How do I convert the std::string to boost::asio::streambuf? Any lead is appreciated.

Initially I used boost::asio::read_until(pNetworkConnector->getSocket(), response, "\r\n"); which initialized boost::asio::streambuf response and I converted it to underlying stream i.e.

boost::asio::streambuf* responsePointer = &response;
iResponseStream.rdbuf(responsePointer);

But now I directly get a std::string using curl like this

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

and used it as

curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &readBuffer);

How can I convert std::string to boost::asio::streambuf or std::streambuf ?

Upvotes: 1

Views: 1433

Answers (1)

Andre Kampling
Andre Kampling

Reputation: 5631

The following code shows how to convert between std::string and boost::asio::streambuf, see it online at ideone:

#include <iostream>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/buffer.hpp>

int main()
{
   /* Convert std::string --> boost::asio::streambuf */
   boost::asio::streambuf sbuf;
   std::iostream os(&sbuf);
   std::string message("Teststring");
   os << message;

   /* Convert boost::asio::streambuf --> std::string */
   std::string str((std::istreambuf_iterator<char>(&sbuf)),
                    std::istreambuf_iterator<char>());

   std::cout << str << std::endl;
}

Upvotes: 3

Related Questions