简体   繁体   English

如何为字符串使用开关和大小写

[英]How to use switch and case for strings

Based on an answer of the following question: How do I transform an IF statement with 2 variables onto a switch function using C? 基于以下问题的答案: 如何使用C将具有2个变量的IF语句转换为切换函数?

I want to develop SWITCH and CASE macros to use it (like switch and case ) for strings. 我想开发SWITCHCASE宏以将其(例如switchcase )用于字符串。

Some thing like that: 像这样的东西:

char buf[256];

SWITCH (buf) {
    CASE ("abcdef"):
        printf ("A1!\n");
        BREAK;
    CASE ("ghijkl"):
        printf ("B1!\n");
        BREAK;
    DEFAULT:
        printf ("D1!\n");
        BREAK;
}

what could be SWITCH and CASE and BREAK and DEFAULT here ? 这里的SWITCHCASE以及BREAKDEFAULT什么?

If you really want it, well, here it is: 如果您确实想要它,那么这里是:

#include <string.h>
#include <stdio.h>
const char *kludge;
#define evilmacro(line) label##line
#define fakelabel(line) evilmacro(line)
#define SWITCH(str) while((kludge = (str)))
#define CASE(str) if(strcmp(kludge, str) == 0) { fakelabel(__LINE__)
#define BREAK break; /* out of while loop */ }
#define DEFAULT if(1) { fakelabel(__LINE__)
int main(int argc, char *argv[]) {
SWITCH (argv[1]) {
    CASE ("abcdef"):
        printf ("A1!\n");
        BREAK;
    CASE ("ghijkl"):
        printf ("B1!\n");
        BREAK;
    DEFAULT:
        printf ("D1!\n");
        BREAK;
}
return 0;
}

Getting rid of the unused labels is left as an exercise for the reader :) 清除未使用的标签留给读者练习:)

EDIT: fwiw, what I would really do is table driven code. 编辑:首先,我真正要做的是表驱动代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SWITCH(S) char *_S = S; if (0)
#define CASE(S) } else if (strcmp(_S, S) == 0) {switch(1) { case 1
#define BREAK }
#define DEFAULT } else {switch(1) { case 1

int main()
{
    char buf[256];

    printf("\nString - Enter your string: ");
    scanf ("%s", buf);

    SWITCH (buf) {
        CASE ("abcdef"):
            printf ("B1!\n");
            BREAK;
        CASE ("ghijkl"):
            printf ("C1!\n");
            BREAK;
        DEFAULT:
            printf ("D1!\n");
            BREAK;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM