Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
How to assign an enum for a switch case from UserInput string in C++

I'm writing this code that takes in a char userinput and uses the switch statement do execute the respective command. However because C++ switch statements can only read ints and enums, I'm not sure how to incorporate this. The user input must be a char. any ideas? I know charInput >> enumInput doesn't work but I'm not sure what to do.

int main(int argc, char** argv) {
    enum charCommand { i, d, s, n, r, a, m, t, p, l, q };
    charCommand enumInput;

    while (mainLoop) {
        cout << "enter valid input" endl;


        char charInput;
        printf("Enter a command: ");
        cin >> charInput;
        charInput >> enumInput;


        switch (charInput) {
        case i: {
            printf("This is case i");
            exit(0);
        } //case i
        default: {
            cout << "invalid command, try again!\n";
        }
        }
    };
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

One way to accomplish this is to map the actual character entered to its corresponding enum:

#include <map>
//...
int main (int argc, char** argv) 
{
    enum charCommand {i,d,s,n,r,a,m,t,p,l,q};
    std::map<char, charCommand> charToEnumMap = {{'i',i}, 
                                                 {'d',d}, 
                                                 {'s',s}}; // Add the rest
    charCommand enumInput;
    while (mainLoop) 
    {
        cout << "enter valid input" endl;
        char charInput;
        printf("Enter a command: ");
        cin >> charInput;
        auto iter = charToEnumMap.find(charInput);
        if ( iter != charToEnumMap.end() ) 
        {
            switch (iter->second) 
            {
                case i : 
                {
                    printf("This is case i");
                    exit(0);
                } //case i
                default: 
                {
                    cout << "invalid command, try again!\n";
                }
            }
        }
    }
}
over 4 years ago · Santiago Trujillo Denunciar

0

There's no need for an enum here. switch works with char because char is convertible to int. So if we define a char as such:

char c = 'a';

..and then switch on it:

switch (c)

This works because 'a' can be converted to int (ASCII value). So this can also be written as:

switch (int(c)) // Same as switch (c)

Example:

#include <iostream>

int main(int argc, char** argv) 
{
    char input; std::cin >> input;

    switch (input)
    {
    case 'a':
        std::cout << 'a' << std::endl;
        break;
    case 'b':
        std::cout << 'b' << std::endl;
        break;
    case 'c':
        std::cout << 'c' << std::endl;
        break;
    default:
        std::cout << "Some other key" << std::endl;
        break;
    }
}

The above example works. For your case, I would rewrite your program as:

#include <iostream>

int main(int argc, char** argv) {

    while (true) {
        std::cout << "enter valid input" << std::endl;

        char charInput;
        printf("Enter a command: ");
        std::cin >> charInput;


        switch (charInput) {
        case 'i':
            printf("This is case i");
            exit(0); //case i
        default:
            std::cout << "invalid command, try again!\n";
            break;
        }
    };
}

Also, consider not using the following in your code:

using namespace std;

..as it's considered as a bad practice. For more info on this, look up why is "using namespace std" considered as a bad practice.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda