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():
http://www.cplusplus.com/reference/string/string/substr/
1
2
3
4
5
6
7
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:
https://en.cppreference.com/w/cpp/regex
http://www.cplusplus.com/reference/regex/
Last edited on
Topic archived. No new replies allowed.