用字符串切换

Jua*_*uan 0 c case-statement switch-statement

不知何故,我的switch语句没有通过我的任何案例,但它不应该进入一个?(我使用/sf/answers/281048701/作为参考).

没有输出,应用程序被阻止后.

#include <stdio.h>

#include <stdlib.h>

#define BADKEY -1
#define string1 1
#define string2 2
#define string3 3
#define string4 4
char *x = "string1";

typedef struct {char *key; int val; } t_symstruct;

static t_symstruct lookuptable[] = {
    { "string1", string1 }, { "string2", string2 }, { "string3", string3 }, { "string4", string4 }
};

#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))

int keyfromstring(char *key) {
    int i;
    for (i=0; i < NKEYS; i++) {
        t_symstruct *sym = lookuptable + i;
        printf("before: \n");
        if (strcmp(sym->key, key) == 0) { //creates the ERROR
            printf("inside: \n");
            return sym->val;
        }
        printf("after: \n");
    }
    return BADKEY;
}

void newFunction(char *uselessVariable) {
    printf("keyfromstring(x): %i \n", keyfromstring(x));
            switch(keyfromstring(x))      {
                case string1:
                   printf("string1\n");
                   break;
            case string2:
                   printf("string2\n");
                   break;
            case string3:
                   printf("string3\n");
                   break;
            case string4:
                   printf("string4\n");
                   break;
           case BADKEY:
                printf("Case: BADKEY \n");
                break;
        }
}

int main(int argc, char** argv) {
    newFunction(line);
    return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*amy 5

  • lookuptable[]在"string1"之后有一个空格,与其他条目不一致.我有一种感觉,你不想要这个.
  • keyfromstring()的增量是sym错误的(这导致了段错误).用...来代替:

int keyfromstring(char *key)
{
    int i;
    for (i=0; i < NKEYS; i++) {
        t_symstruct *sym = lookuptable + i;
        if (strcmp(sym->key, key) == 0)
            return sym->val;
    }
    return BADKEY;
}
Run Code Online (Sandbox Code Playgroud)

要么

int keyfromstring(char *key)
{
    int i;
    for (i=0; i < NKEYS; i++) {
        if (strcmp(lookuptable[i].key, key) == 0)
            return lookuptable[i].val;
    }
    return BADKEY;
}
Run Code Online (Sandbox Code Playgroud)
  • 把你的printf("Case: nothing happen\n");内心default.