c - 用字符串切换

标签 c switch-statement case-statement

不知怎的,我的 switch 语句没有经过我的任何一个案例,但它不应该出现在一个案例中吗? (我使用 https://stackoverflow.com/a/4014981/960086 作为引用)。

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

#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);
}

最佳答案

  • 您的 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;
}

或者

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;
}
<小时/>
  • 将您的 printf("Case:没有发生\n"); 放入 default 中。

关于c - 用字符串切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15295400/

相关文章:

c - 重新声明结构体

c - 可能是内存问题还是其他什么问题?

c - SSE:使用_mm_add_epi32看不到加速

c - 显示切换到现代 C 编译器如何帮助发现错误的示例?

c - 此源代码在 C 中打开一个字符串。它是如何做到的?

java - 开关未按预期工作

c - switch 语句终止后不会重新启动

sql - 如何为 BigQuery 标准 SQL case 语句创建多个 'THEN' 子句?

mysql - 检查同一 post_id 的不同行中的 2 列值时仅获取唯一的 post_id 吗?

sql - 是否可以在 SSIS 表达式中执行 "LIKE"语句?