I have a some if statements nested and was wondering if there's a better way to handle this. What I have works perfectly fine, but maybe there's another way, one that's considered a best practice.
This wants the user to input an book's ISBN in the format of n-n-n-x.
First, recursion is generally confusing, error-prone if not terminated correctly, and should generally be avoided for purposes of "repeat until correct". [I am not against using recursion in places where it may help readability, such as tree structures, if depth scales logarithmically]
Would probably be better to use && to combine your if-statements.
@Ganado - Nicely explained. I knew recursion was frowned upon, but I haven't used the stuff you showed me enough to see them. Your use of std::all_of is one thing I haven't seen before. Anywhere. Or how you returned isbn:
template<class InputIterator, class UnaryPredicate>
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (!pred(*first)) returnfalse;
++first;
}
returntrue;
}
The "first" iterator is the first element of the sequence, while the "last" iterator is one-past-the-end of the sequence, to delimit the sequence.
Essentially, the algorithm runs while it's not the end element. The end element itself is not dereferenced.
Perhaps the following expresses clearer intent: std::all_of(&isbn[0], &isbn[0] + 3, ::isdigit) although the same conceptual issue exists there. (Think of the "3" as being the number of elements checked) and not index 3.