前幾天寫了一篇關於利用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!!