Jaden Williams
Jaden Williams

Reputation: 21

How do I check if a website contains a string in c++?

so I am for the most part a c# coder but I am looking to switch over to c++, I am looking for an answer on how to read a website in c++ then check if it has a certain string, here is my c# code for reference.

string stringexample = "active";
WebClient wb = new WebClient();

string LIST = wb.DownloadString("URL");

if (LIST.Contains(stringexample))

Upvotes: 2

Views: 1158

Answers (2)

Andreas DM
Andreas DM

Reputation: 11018

Standard C++ has no networking utilities but you could use boost::asio library to download the content of a webpage and search for the string "active".

One way to do this:

boost::asio::ip::tcp::iostream stream("www.example.com", "http");
stream << "GET /something/here HTTP/1.1\r\n";
stream << "Host: www.example.com\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n\r\n";
stream.flush();

std::ostringstream ss;
ss << stream.rdbuf();
std::string str{ ss.str() };

if (auto const n = str.find("active") != std::string::npos)
  std::cout << "found\n";
else
  std::cout << "nope\n";

Upvotes: 1

eerorika
eerorika

Reputation: 238401

You can use the following steps:

  1. Request the page using HTTP
  2. Store the response into a std::string
  3. Use std::string::find.

Tricky part here is the step 1. C++ has no standard HTTP client. It doesn't have a standard networking API either. You can find the HTTP spec here: https://www.rfc-editor.org/rfc/rfc2616 which you can use to implement a HTTP client. But as with all programming tasks, you can save a lot of work by using an existing implementation.

Upvotes: 2

Related Questions