前几天写了一篇关于利用switch()中的参数转换成含有字符串的表达式来处理字符串的选择的问题,相信许多的人都和我有同一种感受,就是三目运算符 ?: 用多了老是容易落下一两个括号之类的,有时拗口的选择关系把本身都弄昏了。在看《C primer plus》第十四章的时侯,讲到了enum类型的数据,及其用法。其中涉及到一个swith()case的选择语句,感受很是好,后来查查谭浩强的《C程序设计》也有个相似的小例子。
仍是以上次的那个内容做例子。程序以下:
/************************************************************************/
/*Name : windows_main */
/*Author : Aben */
/*Date : 21/03/2008 */
/************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum choice {fingerPrintIdentify, osPatchDetect, softAssertAna, netAppSoftDetect, systemConfigAnaly, hardwareInterfaceAnaly};
const char *choices[] = {
"fingerPrintIdentify", "osPatchDetect", "softAssertAna",
"netAppSoftDetect", "systemConfigAnaly", "hardwareInterfaceAnaly"};
void del(char str[]); //因为使用fgets()函数,会得到最后的回车符,用此函数除去之
int main(int argc, char *argv[])
{
FILE *fp = NULL;
enum choice i;
char buf[30];
if ((fp = fopen("config\\server_test_config.txt","r")) == NULL)
{
printf("Can not open the config file, please make sure it's exist!\n");
fclose(fp);
exit(0);
}
memset(buf, '\0', sizeof(buf));
while (fgets(buf, 30, fp))
{
del(buf);
printf("%s",buf);
for(i=fingerPrintIdentify; i<=hardwareInterfaceAnaly; i++)
{
if (strcmp(buf, choices[i]) == 0)
{
break;
}
}
switch(i)
{
case fingerPrintIdentify:
printf("fingerPrintIdentify is exist!\n");
break;
case osPatchDetect:
printf("osPatchDetect is exist!\n");
break;
case softAssertAna:
printf("softAssertAna is exist!\n");
break;
case netAppSoftDetect:
printf("netAppSoftDetect is exist!\n");
break;
case systemConfigAnaly:
printf("systemConfigAnaly is exist!\n");
break;
case hardwareInterfaceAnaly:
printf("hardwareInterfaceAnaly is exist!\n");
break;
default:
printf("ERROR!\n");
break;
}
memset(buf, '\0', sizeof(buf));
}
system("PAUSE");
return 0;
}
void del(char str[])
{
char *found;
found = strchr(str, '\n');
if (found)
{
*found = '\0';
}
}
这里有一点要说明的是,若是你的编译器不支持C99标准的话,就不要试了,个人Visual C++ 6.0编译器也不支持,总是给我报enum类型的数据不可以进行i++的运算,我把它修改成i=i+1后而后就报不能将enum类型的数据转换成int类型进行此种运算。最后,仍是将这些东西考在dev-C++(支持C99的编译器)上运行,结果以下:
netAppSoftDetectnetAppSoftDetect is exist!
systemConfigAnalysystemConfigAnaly is exist!
softAssertAnalyERROR!
hardwareInterfaceAnalyhardwareInterfaceAnaly is exist!
osPatchDetectosPatchDetect is exist!
fingerPrintIdentifyfingerPrintIdentify is exist!
请按任意键继续. . .
bingo!!