Search code examples
c++algorithmstlistream

Idiomatic way to know if an istream starts with a string in C++?


Suppose you have two strings and you want to know whether one is a prefix of the other. Here is one way to do it in C++:

std::string s = ...;
std::string prefix = ...;
bool sStartsWithPrefix = std::equal(prefix.begin(), prefix.end(), s.begin());

But suppose that instead of s you have an input stream:

std::istream& inputStream = ...;
std::string prefix = ...;
bool inputStreamStartsWithPrefix = ?

Sure, we could compute inputStreamStartsWithPrefix by writing a for loop. But how to do it idiomatically (without a for loop, with an algorithm)?


Solution

  • You can use a std::istream_iterator in combination with std::equal like

    std::istringstream is("foobar");
    std::string prefix = "foo";
    bool inputStreamStartsWithPrefix = std::equal(prefix.begin(), prefix.end(), std::istream_iterator<char>(is));