How to make a switch case for keyboard input in c++?

by emilia_hackett , in category: General Help , 2 months ago

How to make a switch case for keyboard input in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by gabrielle.kub , 2 months ago

@emilia_hackett 

To make a switch case for keyboard input in C++, you can use the switch statement along with the cin function to read the keyboard input. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

int main() {
    char choice;

    cout << "Enter your choice (A, B, C, D): ";
    cin >> choice;

    switch(choice) {
        case 'A':
            cout << "Option A selected." << endl;
            break;
        case 'B':
            cout << "Option B selected." << endl;
            break;
        case 'C':
            cout << "Option C selected." << endl;
            break;
        case 'D':
            cout << "Option D selected." << endl;
            break;
        default:
            cout << "Invalid choice." << endl;
    }

    return 0;
}


In this example, the user is prompted to enter a character and the input is stored in the choice variable. The switch statement is then used to check the value of choice against different cases. Depending on the input, the corresponding block of code will be executed. If none of the cases match, the default block is executed.