...

/

Using if In A Search Statement

Using if In A Search Statement

Let's test the 'if' statement feature we discussed in the last lesson.

We'll cover the following...

We learned that C++17 allows us to specify a new variable which can be used in the condition. This variable is inside the if condition scope:

Press + to interact
if (auto val = GetValue(); condition(val))
// on success
else
// on false...

Let’s see if this is useful. Say you want to search for a few things in a string:

#include <iostream>
using namespace std;
int main() {
// your code goes here
const std::string myString = "My Hello World Wow";
const auto pos = myString.find("Hello");
if (pos != std::string::npos)
std::cout << pos << " Hello\n";
const auto pos2 = myString.find("World");
if (pos2 != std::string::npos)
std::cout << pos2 << " World\n";
}

As you can see, you have to use different names for pos or enclose it with a separate scope, otherwise the code will fail as it does in the ...