如何切换和大小写字符串? [英] How to switch and case for string?
本文介绍了如何切换和大小写字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
#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;
}
}
如果我使用 gcc -E
生成预处理器代码,我将获得以下代码
If I generate the pre-processor code with gcc -E
, I will get the following code
int main()
{
char buf[256];
printf("\nString - Enter your string: ");
scanf ("%s", buf);
char *_S = buf;
if (0) {
} else if (strcmp(_S, "abcdef") == 0) {switch(1) { case 1:
printf ("B1!\n");
};
} else if (strcmp(_S, "ghijkl") == 0) {switch(1) { case 1:
printf ("C1!\n");
};
} else {switch(1) { case 1:
printf ("D1!\n");
};
}
}
但是对于某些在代码中间定义 char * _S = buf;
的gcc而言,它不是狼来了,并且可能会提供编译错误
But for some gcc defining char *_S = buf;
in the middle of the code is not wolcome and could provide compilation error
如何在宏中修复该问题?
How to fix that in my macro?
请不要建议将 char * _S
定义为全局(在 main
中)
Please do not suggest to define char *_S
as global (out of the main
)
推荐答案
哦,不!
我在不要使用它是非常可怕的,如果要避免if-else,可以在不折磨编译器的情况下进行操作,请考虑使用一对字符串:
Don't use it is very very horrific, if you want to avoid if-else you can do it without torturing the compiler, consider using pair of strings:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[256];
const char *ap[] = {
"abcdef", "B1!\n",
"ghijkl", "C1!\n",
NULL , "D1!\n",
}, **p = ap;
printf("\nString - Enter your string: ");
scanf ("%s", buf);
while (*p) {
if (strcmp(buf, *p) == 0) break;
p += 2;
}
printf("%s", *(++p));
return 0;
}
这篇关于如何切换和大小写字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文