简体   繁体   中英

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

so I am for the most part ac# 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))

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://tools.ietf.org/html/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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM