前几天写了一篇关于利用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!!