Need help with a "general" if statement c++

closed account (E3b5y60M)
okay, so basically i want to make something like this: Say i have an if statement with a string like this:

getline (cin, string);
if (string == "hello my name is joe"){
cout<<"cool name!";

some thing like that. but could i make it to where if you say a general thing like "hello my name is ____" and if you have a certain statement in that string and then whatever words following after then the if statement will still work. Like it only looks for the word hello and then it executes the statement.
Last edited on
Yes. You can compare to just the first N characters. For more general matching, you can use a "regular expression" which basically specifies a pattern to match.

Finally, if you have several different things to match, consider storing them in an array and using a loop to check them one at a time.
Prefix and suffix of string are relatively easy with substr():
string line;
getline( cin, line );
string greet = "hello my name is ";
if ( greet.size() < line.size() &&
     line.substr( 0, greet.size() ) == greet ) {
  cout << line.substr( greet.size() ) << " is a cool name!";

The regular expressions:
Last edited on
Registered users can post here. Sign in or register to post.