题目:一个简单的格式分析程序。浮点数的组成规则已知。求是不是正确的数字。有限自动机。
注意:有些情况如没有e的情况,不要忘了考虑
#include <cstdio>
#include <string.h>
#include <cstdlib>
#include <cmath>
#include <ctgmath>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//理解有限状态机
/*
pre_num 数分析前状态
sign1 数值部分符号
pre_point 数值部分小数点前
point 小数点
fraction 数值部分小数点后
e 指数符号
sign2 指数部分符号
exp 指数部分的的指数状态
followblack 常数后的空格
error 错误
*/
//cin进行字符变量输入,自动过滤头部空格
int main(){
enum Status{pre_num,sign1,pre_point,point,fraction,e,sign2,exp,error};
char m;
char str[1000];//存读入的数字
Status state;
while(cin >> str && strcmp(str, "*")!=0){
int i = 0;
m = str[i];
state = pre_num;
while (m != '\0') {
switch (state) {
case pre_num: if(m=='+' || m=='-'){state = sign1;break;}
else if(m>='0' && m<='9'){state = pre_point;break;}
else {state = error;break;}
case sign1: if(m>='0' && m<='9'){state = pre_point;break;}
else {state = error;break;}
case pre_point:if(m=='.'){state = point;break;}
if(m=='e' || m=='E'){state = e;break;}//不一定是小数的情况
if(m>='0' && m<='9'){state = pre_point;break;}//123.1情况
else state = error;break;
case point: if(m>='0' && m<='9'){state = fraction;break;}
else state = error;break;
case fraction: if(m>='0' && m<='9'){state = fraction;break;}
else if(m=='e' || m=='E'){state = e;break;}
else state = error; break;
case e: if(m=='+' || m=='-'){state = sign2;break;}
else if(m>='0' && m<='9'){state = exp;break;}
else state = error;break;
case sign2: if(m>='0' && m<='9'){state = exp;break;}
else state = error;break;
case exp: if(m>='0' && m<='9'){state = exp;break;}
else state = error;break;
case error: goto lable;
}
m = str[++i];
}
lable:if (state == error) {printf("%s is illegal.\n",str);}
else if(state == fraction || state == exp) printf("%s is legal.\n",str);
else printf("%s is illegal.\n",str);
}
return 0;
}