0

I was hoping to find out if there is a command in C++ that will find similar variations to input and accept those as well as the exact answers in an if statement.

For example:
If I have a user type in "Hi"
and the if statement needs to accept "hi" to be valid, how can I make it also accept that without having to type in all the variations myself which is what "||" does.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 4
    You want a case insensitive comparison? If so see [here](http://stackoverflow.com/q/11635/380621) – tjm Dec 18 '10 at 02:31
  • 1
    Doesn't C++ have some function for changing the case of a string? – Ignacio Vazquez-Abrams Dec 18 '10 at 02:32
  • @Ignacio -- In the standard library? Not a single function. There's toupper and tolower which act on single chars. You can combine them with transform to act on a whole string though. Or you can use boost::to_upper or boost::to_upper_copy. – Benjamin Lindley Dec 18 '10 at 02:43
  • 2
    "Similar" is under-specified. Do you have a list of everything that counts as "similar"? Does "similar" mean "case-insensitive equal". Does it mean "the same except that the first character is allowed to be different case"? Does it mean, "the same except that the first character can be anything"? There's certainly no C++ function to decide for you what "similar" means ;-) – Steve Jessop Dec 18 '10 at 02:43
  • He may be asking for a regular expression library in which the pipe represents alternates? – dmckee --- ex-moderator kitten Dec 18 '10 at 02:51

4 Answers4

2

How about computing some kind of edit distance. You could weight case changes with a very low distance and accept all inputs that are below a certain threshold.

ltjax
  • 15,837
  • 3
  • 39
  • 62
0

If there are a lot of variations, and it's cumbersome to enumerate them, you may want to consider running the input through a regex parser. One that's lightweight is T-Rex.

Ravi
  • 3,718
  • 7
  • 39
  • 57
0

Uppercase the strings, then compare the uppercased strings.

Note that theoretically this can run afoul of various national language conventions for uppercasing, which appears to be one reason that the C++ standard library has very poor support for uppercasing (if it can't be done 100% perfectly, then let's not do it).

In practice, though, any problematic national character string can simply be avoided.

Cheers & hth.,

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

Lowercase the input string.
Then compare:

std::string   answer;
std::cin >> answer;

std::transform(answer.begin(), answer.end(), answer.begin(), ::tolower);
if (answer == "hi")
{
    std::cout << "Wrong answer\n";
}
Martin York
  • 257,169
  • 86
  • 333
  • 562