Currently I can run my program but my code consists of a lot of repetition which looks something like:
while(option != 'E' && option != 'D' && option != 'P' && option != 'Q' &&
option != 'e' && option != 'd' && option != 'p' && option != 'q') {
// Some code here
}
or:
while(cType != 'S' && cType != 'L' && cType != 'O' && cType != 'Q' &&
cType != 's' && cType != 'l' && cType != 'o' && cType != 'q') {
// Some code here
}
What's the fastest way to shorten above code?
(Is there any way beside using additional function?)
const char invalidChars[] = "edpq";
while (strchr(invalidChars, tolower(option)) != 0) {
...
}
You could initialize a string containing the characters you want to match, then use find
, which returns npos
if no match was found:
string match = "SLOQsloq";
while (match.find(cType) == string::npos)
...
You could get rid of half of the conditions with std::tolower
while(std::tolower(option) != 'e' && std::tolower(option) != 'd' && std::tolower(option) != 'p' && std::tolower(option) != 'q')
You could also use a std::string
and it's find
member function like:
std::string options = "edpq";
//...
while (options.find(std::tolower(option)) == std::string::npos)
You could simplify the logic and make things more readable by using an std::set
and checking if the set contains (or doesn't contain) the variable we're comparing to:
std::set<char> someChars { 'a', 'b', 'c' };
if(someChars.find(myChar) != someChars.end()) {
// myChar is either 'a', 'b', or 'c'
}
The condition in most other languages would be written more cleanly as something like someChars.contains(myChar)
(but C++'s set interface is very minimal).
However, for a small number of comparisons, your method is probably faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With