Using an Array in a Switch Case Statement

Asked 2 years ago, Updated 2 years ago, 30 views

char sel1[10];
int teamsel;

cin >> sel1;

switch (*sel1) {

    case "kt" : 
        teamsel = 1;

    case "Fin" :
        teamsel = 2;

}

I want to use it like this. How shall I do it?

c++ switch문

2022-09-22 15:09

2 Answers

String is not allowed in Switch statements It is recommended that you create a separate ID that points to the specified string and compare it.

#include <iostream>
#include <map>

#define BUFFER 256

int main()
{
    enum EnumTeam
    {
        eTeamKt = 1, eTeamFin
    };
    std::map<std::string, EnumTeam> teamList;

    char str[BUFFER] = "";
    int select = 0;
    teamList["Kt"] = eTeamKt;
    teamList["Fin"] = eTeamFin;

    std::cout << "Team Select >> ";

    std::cin >> str;    //  Input

    switch (teamList[str])
    {
    case eTeamKt:
        select = (int)eTeamKt;  break;
    case eTeamFin:
        select = (int)eTeamFin; break;
    }

    std::cout << "Team : " << select << std::endl;

    system("pause");
    return 1;
}


2022-09-22 15:09

The switch statement cannot contain a string.

Only available

number or letters and

.

Characters are also actually applied internally to the ascii numeric value.

To use a string, use the if statement to use the entered string

Convert to a separate integer value and use it for the switch door.


2022-09-22 15:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.