我对编程还比较陌生,有一个问题。 最近,我们的教授要求我们使用两个char变量(day)来接收来自用户的输入。 代码的底部片段可以很好地检查,以确保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;
}
您可以编写一个将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
这是一个演示。
这应该可以满足使用2个char
输入的要求。
通常首先使用toLower
或toUpper
将char
变量转换为正确的大小写。 我喜欢使用toLower
-它看起来稍微好一点。
dayOne = tolower(dayOne);
dayTwo = tolower(dayTwo);
while (
(dayOne != 'm' || dayTwo != 'o') &&
(dayOne != 't' || dayTwo != 'u') &&
(dayOne != 'w' || dayTwo != 'e') &&
(dayOne != 't' || dayTwo != 'h') &&
(dayOne != 'f' || dayTwo != 'r') &&
(dayOne != 's' || dayTwo != 'a') &&
(dayOne != 's' || dayTwo != 'u'))
{
...
}
您可以通过使用memcmp
同时比较两个字符来进一步更改它,但我不确定这样做会简化代码。
另一种值得提及的方法是组织数据,以便您可以对数据使用std函数(std::find
)
// Example program
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
int main()
{
const std::vector<std::string> days = {
"mo", "tu", "we", "th", "fr", "sa", "su"
};
bool found = false;
while (found == false) {
char dayOne, dayTwo;
std::cout << "Please enter the first letter of the day" << std::endl;
std::cin >> dayOne;
std::cout << "Please enter the second letter of the day" << std::endl;
std::cin >> dayTwo;
std::string fullDay;
fullDay += std::tolower(dayOne);
fullDay += std::tolower(dayTwo);
found = std::find(days.begin(), days.end(), fullDay) != days.end();
std::cout << (found ? "correct day " : "invalid day, please try again ")
<< fullDay
<< std::endl;
}
}
在这里运行