Me myself and I
Me myself and I

Reputation: 57

Switch statement, two similar cases in different case

If I want to create a menu with options, so e.g

If I have two cases, A and B, within those they have the option to write C. A C and BC as input should be different things, and not conflict. How would that work?

char ch;

cout << "Write in command: ";
cin >> ch; 

switch(ch) {
    case 'A': {
        cin >> ch;
        case 'C': cout << "C"; break;
        break;
    }
    case 'B': {
        cin >> ch;
        case 'C': cout << "C"; break;
        break;
    }

}

Upvotes: 0

Views: 389

Answers (1)

Rabster
Rabster

Reputation: 1013

You have to use another switch case or if statement for each of the cases.

I'd personally recommend using an if statement if you're going to be using a small amount of items since another switch case would make it ugly in my eyes.

Nested switch case.

switch(ch) {
    case 'A': {
        cin >> ch;
        switch (ch) {
            case 'C': cout << "C"; break;
        }
        break;
    }
    case 'B': {
        cin >> ch;
        switch (ch) {
            case 'C': cout << "C"; break;
        }
        break;
    }
}

Nested if statement.

switch(ch) {
    case 'A': {
        cin >> ch;
        if (ch == 'C') {
            std::cout << 'C';   
        }
        break;
    }
    case 'B': {
        cin >> ch;
        if (ch == 'C') {
            std::cout << 'C';   
        }
        break;
    }
}

Upvotes: 1

Related Questions