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