用enum类型数据解决switch case选择字符串的问题

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

转载于:https://my.oschina.net/ypimgt/blog/89647

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值