【问题标题】:Map number between 1 and 12 to month name将 1 到 12 之间的数字映射到月份名称
【发布时间】:2016-02-11 05:40:14
【问题描述】:

我需要制作一个根据用户输入显示月份的程序。例如,如果用户输入8,它将显示August。我不能使用if 语句或任何检查条件的东西。我还必须使用函数.substr()。我必须使用包含所有月份的字符串。

例如,string months = "January...December";

【问题讨论】:

  • 向我们展示您迄今为止所做的尝试。
  • 您有什么问题吗?
  • 由于我没有任何反馈,请再给我一票否决票,以便我获得同行压力徽章...

标签: c++


【解决方案1】:

编辑:将“用户输入检查”if 替换为 try-catch 块以符合 OP 限制:“我不能使用 if 语句

您可以格式化“月份”string 以满足您的需要。最长的月份名称是九月(9 个字母),所以每个月最多用 9 个字母填写“月份”:

std::string months="January  February March    April    May      June     July     August   SeptemberOctober  November December ";

然后您可以只使用用户输入作为substr 的索引,假设用户输入将在 1 到 12 之间。即:

input--;    // Indexes start at 0
input *= 9; // Scale it to word length

// Use substr as requested. Remember 9 is the max length of the month name
std::string selectedMonth = months.substr(input, 9); 

如果需要,您可以按照here 的说明修剪尾随空格

请注意这是一个易于理解的教学示例,还有很大的改进空间。完整代码:

#include <iostream>
using namespace std;

int main() 
{

    int input = 0;
    cin >> input;

    string months="January  February March    April    May      June     July     August   SeptemberOctober  November December ";

    input--;    // Indexes start at 0
    input *= 9; // Scale it to word length

    string selectedMonth;
    try
    {
        // Use substr as requested. Remember 9 is the max length of the month name
        selectedMonth = months.substr(input, 9);
    }
    catch (out_of_range &ex)
    {
        cout << "error: input must be in the range [1, 12]";
    }
    // Trim it before outputting if you must
    cout << selectedMonth;
    return 0;
}

【讨论】:

  • 还有另一个没有评论的反对票。愿意解释为什么这样我可以改进答案吗?我刚刚为 OP 的要求提供了一个可能的解决方案:没有如果,必须使用 .substr() 和。必须使用包含所有月份的字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 2021-04-30
  • 2021-02-28
  • 2013-05-05
  • 2020-12-07
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多