最近,我们的教授要求我们使用两个char
变量(天)来接收用户的输入。
下面的代码可以很好地用作检查,以确保Mo,Tu,We,Th,Fr,Sa,Su是唯一一起成对输入的两个字符。如果接收到其他任何内容作为输入,它将循环并询问用户有效的输入。
输入应不区分大小写,例如,可接受"mO"
和"tu"
。似乎正在发生大量重复。有办法清理吗?
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(), '\n');
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;
}
最佳答案
您可以编写一个fold-expression来将2个字符与一个字符串进行比较:
template<typename ...Days>
bool any_of(char a, char b, Days ...days)
{
return (... || (a == days[0] && b == days[1]));
}
然后像这样使用它:
while (! any_of(std::tolower(dayOne), std::tolower(dayTwo), "mo", "tu", "we", "th", "fr", "sa", "su"))
// keep asking for input
这是demo。
这应该满足使用2个
char
输入的要求。