所以基本上我想在 C 中创建一个程序,您将输入 2 个字符长的字符串(字母和数字 ex.r1、u2、i3、i4、r6 的混合)作为我程序的输入。后来我想把这个字符串放在 SWITCH 中。这可能吗? 这是我的简单源代码。如有错误请指正:)
#include <stdio.h>
int main(void)
{
char string[2];
scanf("%s", &string);
switch (string)
{
case 'u1' :printf("%s\n", string);break;
default :printf("ERROR");break;
}
return 0;
}
最佳答案
根据字符串创建代码并打开它。
#define Code(a,b) (a + 256*b)
char string[3]; // 3 not 2
if (scanf("%2s", string) != 1) { // No &
Handle_Error();
}
int scode = Code(string[0], string[1]);
switch (scode) {
case Code('u', '1') : printf("%s\n", string); break;
case Code('r', '2') : printf("r2\n"); break;
...
default :printf("ERROR");break;
}
switch(x)
需要 x
的整数值,string
是一个数组。所以原来的方法行不通。
该程序可以使用基于字符串的整数作为 x
,并使用相同的方法生成 case
值。由于只对字符串的前 2 个 char
感兴趣,因此 int
值是唯一的。
关于c - 初学者,带源代码的 C 语言 switch 中的字符串。可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293084/