Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

c++ - How can I better check whether two char variables are in some set of values?

Recently, our professor has requested that we use two char variables (day) to receive the input from the user.

The code below works fine as a check to ensure that either Mo, Tu, We, Th, Fr, Sa, Su are the only two characters which are entered together as a pair. If anything else is received as input, it'll loop and ask the user for valid input.

The input should be case-insensitive, meaning that, for example, "mO" and "tu" are acceptable. It seems like there is a lot of repetition that is happening. Is there a way to clean this up?

cout << "Please enter the day of the week did you made the long distance call (Mo Tu We Th Fr Sa Su): ";
cin >> dayOne >> dayTwo;

while ((dayOne != 'M' && dayOne != 'm' || dayTwo != 'O' && dayTwo != 'o') &&
       (dayOne != 'T' && dayOne != 't' || dayTwo != 'U' && dayTwo != 'u') &&
       (dayOne != 'W' && dayOne != 'w' || dayTwo != 'e' && dayTwo != 'E') &&
       (dayOne != 'T' && dayOne != 't' || dayOne != 'H' && dayTwo != 'h') &&
       (dayOne != 'F' && dayOne != 'f' || dayTwo != 'R' && dayTwo != 'r') &&
       (dayOne != 'S' && dayOne != 's' || dayTwo != 'A' && dayTwo != 'a') &&
       (dayOne != 'S' && dayOne != 's' || dayTwo != 'U' && dayTwo != 'u'))
{
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '
');
    cout << endl << "You have entered an invalid day. Please re-enter a day in the correct format (Mo Tu We Th Fr Sa Su): ";
    cin >> dayOne >> dayTwo;
}
question from:https://stackoverflow.com/questions/62411825/how-can-i-better-check-whether-two-char-variables-are-in-some-set-of-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could write a fold-expression that compares 2 characters to a string:

template<typename ...Days>
bool any_of(char a, char b, Days ...days)
{
    return (... || (a == days[0] && b == days[1]));
}

and then use it like this:

while (! any_of(std::tolower(dayOne), std::tolower(dayTwo), "mo", "tu", "we", "th", "fr", "sa", "su"))
    // keep asking for input

Here's a demo.

This should satisfy the requirement of using 2 char inputs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...