Why the switch statement cannot be applied on strings?

前端 未结 20 2967
离开以前
离开以前 2020-11-22 03:58

Compiling the following code and got the error of type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    sw         


        
20条回答
  •  梦谈多话
    2020-11-22 04:39

    You can use switch on strings. What you need is table of strings, check every string

    char** strings[4] = {"Banana", "Watermelon", "Apple", "Orange"};
    
    unsigned get_case_string(char* str, char** _strings, unsigned n)
    {
        while(n)
        {
            n--
            if(strcmp(str, _strings[n]) == 0) return n;
        }
        return 0;
    }
    
    unsigned index = get_case_string("Banana", strings, 4);
    
    switch(index)
    {
        case 1: break;/*Found string `Banana`*/
        default: /*No string*/
    }
    

提交回复
热议问题