Reputation: 47
I've a simple question about conditions in if
and for
or while
loops.
Is there any way that lets me verify this condition with less lines of code?
if (are_you_sure != "Si" && are_you_sure != "si" && are_you_sure != "No" && are_you_sure != "no")
I don't think I can minimize the code above, but I would like to be sure.
Upvotes: 3
Views: 214
Reputation: 60393
You can write a lot less code, and make it more readable, if you have a function that does that for you:
if (none_of( are_you_sure, "Si", "si", "No", "no"))
// ...
Of course, that function has to be written, but it's not too much code with c++17 fold-expressions:
template<typename T, typename ...Opts>
auto none_of(T val, Opts ...opts)
{
return (... && (val != opts));
}
This has some nice properties; it can take any number of arguments, and also be used with types other than strings:
int n = 42;
if (none_of( n, 1, 2, 3))
// ...
Make sure to name the function well, as that affects readability a lot.
Upvotes: 7