-5

I need to make a program that displays a month based on the user input. For example, if the user inputs 8, it will display August. I cannot use if statements or anything that checks for a condition. I also have to use the function .substr(). I have to use a string that contains all the months.

For example, string months = "January...December";

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Luis
  • 1

1 Answers1

-2

EDIT: Replaced the "user input check" if for a try-catch block in order to comply with OP restriction: "I cannot use if statements"

You could just format the "months" string to suit your needs. The longest month name is September (9 letters), so fill up "months" with spaces up to 9 letters for each month:

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

Then you could just use the user input as index for the substr, assuming user input will be between 1 and 12. i.e.:

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); 

If needed, you could trim the trailing whitespaces as explained here

Please take into account this is a didactic example to be easily understood, with plenty of room for improvement. Full code:

#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;
}
Community
  • 1
  • 1
Nacho
  • 1,104
  • 1
  • 13
  • 30
  • And there goes another downvote without a comment. Care to explain why so I can improve the answer? I just provided a possible solution for what OP asked: no if's, must use .substr() and. have to use a string that contains all the months. – Nacho Feb 19 '16 at 04:51