用c++写一个识别四则运算的有穷自动机
时间: 2023-04-04 21:02:56 浏览: 74
好的,我可以回答这个问题。以下是一个简单的用 C 语言编写的识别四则运算的有穷自动机:
#include <stdio.h>
#include <ctype.h>
int main() {
int state = 0;
char c;
while ((c = getchar()) != EOF) {
switch (state) {
case 0:
if (isdigit(c)) {
state = 1;
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
state = 2;
} else if (c == '(') {
state = 0;
} else if (c == ')') {
state = 0;
} else if (isspace(c)) {
state = 0;
} else {
printf("Invalid input\n");
return 1;
}
break;
case 1:
if (isdigit(c)) {
state = 1;
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
state = 2;
} else if (c == ')') {
state = 0;
} else if (isspace(c)) {
state = 0;
} else {
printf("Invalid input\n");
return 1;
}
break;
case 2:
if (isdigit(c)) {
state = 3;
} else if (c == '(') {
state = 0;
} else {
printf("Invalid input\n");
return 1;
}
break;
case 3:
if (isdigit(c)) {
state = 3;
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
state = 2;
} else if (c == ')') {
state = 0;
} else if (isspace(c)) {
state = 0;
} else {
printf("Invalid input\n");
return 1;
}
break;
}
}
if (state == 1 || state == 3) {
printf("Valid input\n");
} else {
printf("Invalid input\n");
}
return 0;
}
这个程序可以识别输入的四则运算表达式是否合法。如果输入的表达式合法,程序会输出"Valid input",否则会输出"Invalid input"。