我正在构建一个代码,该代码需要一个月的字符串,并且我想使用重载增加本月的时间,以便我可以得到2月。
好吧,我尝试使用switch case语句将month转换为1到12之类的数字,我增加了该值,但是现在我需要另一个switch case将数字再次转换为string。
class DayOfYear
{
private:
int day;
string month;
public:
DayOfYear(){}
DayOfYear(int d, string m){
day = d;
month = m;
if(d > 31 && d < 1){
cout<<"Invalid input."<<endl;
}
}
string check() //To check the month
{
switch(month)
{
case "January":
return 1;
break;
case "February":
return 2";
break;
case "March":
return 3;
break;
// similarly upto november
case "December":
return 12;
break;
default:
cout<<"Invalid Input.";
break;
}
}
DayOfYear operator++(){
DayOfYear d;
d.day = day++;
if(d.day>31){
d.day = 1;
++d.month;
}
}
我不希望回答,我希望得到方法。
答案 0 :(得分:1)
您不能在C ++中打开std :: string。看来您想做这样的事情:
#include <string>
#include <cctype>
#include <map>
const char* intAsMonth(int index)
{
if(index < 1 || index > 12)
return "invalid";
const char* const months[] = {
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
};
return months[index - 1];
}
int monthAsInt(std::string month)
{
// make lower case
std::transform(month.begin(), month.end(), month.begin(),
[](char c){ return std::tolower(c); });
static std::map<std::string, int> months = {
{"january", 1},
{"february", 2},
{"march", 3},
{"april", 4},
{"may", 5},
{"june", 6},
{"july", 7},
{"august", 8},
{"september", 9},
{"october", 10},
{"november", 11},
{"december", 12}
};
auto it = months.find(month);
if(it == months.end())
return -1; // did not find
return it->second;
}
int nextMonth(int month)
{
if(++month > 12) month = 1;
return month;
}
int prevMonth(int month)
{
if(--month < 1) month = 12;
return month;
}
std::string nextMonth(const std::string& month)
{
return intAsMonth(nextMonth(monthAsInt(month)));
}
std::string prevMonth(const std::string& month)
{
return intAsMonth(prevMonth(monthAsInt(month)));
}