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

by emilia_hackett , in category: General Help , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by gabrielle.kub , a year 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.

by aliya.yundt , 9 months ago

@emilia_hackett 

This code snippet demonstrates how you can create a switch case using keyboard input in C++. It prompts the user to enter a character ('A', 'B', 'C', or 'D'), reads the input using cin, and then utilizes a switch statement to execute the relevant case based on the user's input. Lastly, it has a default case to handle situations where the input does not match any of the predefined cases.

Related Threads:

How to change keyboard language in ubuntu?
How to switch user in ubuntu?
How to switch wireless networks on Ubuntu?
How to make alias of a linux command?
How to make a thread wait for another one in linux?
How can I make HTTPS available for clients on a Linux server?