0

I'm trying to write a program using the switch() function such that when the user inputs 6 7 or 8, it returns "June", "July", and "August" respectively. When the user enters any other number between 1-12, it should return "Not summer", and any other input should return "Invalid". As shown in my code below, is there any way to express lines 16-24 in just one line?

    int month;

    cout << "Enter a number to determine what month it is: ";
    cin >> month;

    switch (month) {
        case 6:
            cout << "June";
            break;
        case 7:
            cout << "July";
            break;
        case 8:
            cout << "August";
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 9:
        case 10:
        case 11:
        case 12:
            cout << "Not summer";
            break;
        default:
            cout << "Your input is out of range";
 }
Mysterai
  • 19
  • 3
  • 1
    What about `if(month>=6 && month<=8)` + array of months as strings? – Quimby Oct 15 '21 at 01:01
  • 1
    One way is to get rid of those other cases and make the default go `if ( month < 1 || month > 12 )` . Another would be to move that test outside of the switch, e.g. `if (....) { errror.... } else switch...` – M.M Oct 15 '21 at 01:06
  • Which are lines 16-24? – user207421 Oct 15 '21 at 03:13

2 Answers2

2

I would re-write the switch as follows:

int month;

cout << "Enter a number to determine what month it is: ";
cin >> month;

const char* summerMonths[] = {"June", "July", "August"};

switch (month) {
    case 6:
    case 7:
    case 8:
        cout << summerMonths[month-6];
        break;
    default:
        if (month >= 1 && month <= 12)
            cout << "Not summer";
        else
            cout << "Your input is out of range";
        break;
}

In which case, you may as well just get rid of the switch altogether:

int month;

cout << "Enter a number to determine what month it is: ";
cin >> month;

const char* summerMonths[] = {"June", "July", "August"};

if (month >= 6 && month <= 8) {
    cout << summerMonths[month-6];
else if (month >= 1 && month <= 12)
    cout << "Not summer";
else
    cout << "Your input is out of range";
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
-3

you can use case 1 ... 5: and case 9 ... 12:

Thomas Q
  • 850
  • 4
  • 10
  • 3
    Worth noting this is not standard C++. – Quimby Oct 15 '21 at 01:00
  • 2
    The GNU C compiler [supports this as a non-standard extension](https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html). But it requires 3 dots rather than 2, and spaces when using integers, eg: `case 1 ... 5:` – Remy Lebeau Oct 15 '21 at 01:19