递归检查表达式有效性的布尔函数
Boolean Function to Check Validity of Expression Recursively?
我想创建一种形式为的解析器
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
bool isValid(istringstream& is)
{
char ch;
is.get(ch); //I know get(ch) is a good start but this is as for as I got :)
.......
....
}
int main()
{
string s;
while(getline(cin,s))
{
istringstream is(s);
cout<<(isValid(is)? "Expression OK" : "Not OK")<<endl;
}
}
一个布尔函数,如果char的序列为"5"或"(5+3)"、"((5/3)+6)"或"((4+2)+1)+6"形式,则返回TRUE。。。等等,对于任何其他情况为FALSE
基本上,如果表达式是个位数或形式为"开括号个位数加符号个位数闭括号",则该表达式将被视为有效
有效表达式=个位数
和
有效表达式=(有效表达式+无效表达式)
考虑到上面表单的大小没有限制(左括号和右括号的数量等),我想使用递归来实现这一点
作为一个新手,我…谢谢你的帮助!
要执行递归解决方案,您需要先将字符串读取到缓冲区中,然后执行以下操作:
int expression(char* str) {
if (*str == '(') {
int e1 = expression(str + 1);
if (e1 == -1 || *(str + 1 + e) != '+') {
return -1;
}
int e2 = expression(str + 1 + e + 1);
if (e2 == -1 || *(str + 1 + e + 1 + e2) != ')') {
return -1;
}
return 1 + e1 + 1 + e2 + 1;
}
if (*str >= '0' || *str <= '9') {
return 1;
}
return -1;
}
bool isvalid(char* str) {
int e1 = expression(str);
if (e1 < 0) {
return false;
}
if (e1 == strlen(str)) {
return true;
}
if (*(str + e1) != '+') {
return false;
}
int e2 = expression(str + e1 + 1);
if (e2 < 0) {
return false;
}
return (e1 + 1 + e2 == strlen(str));
}
基本上,表达式函数在其参数处返回有效表达式的长度。如果它的参数以圆括号开头,那么它会获取其后表达式的长度,然后验证加号,然后验证下一个表达式后的右括号。如果参数以数字开头,则返回1。如果出现问题,返回-1。然后使用这个函数,我们可以通过一些和和字符串的长度来判断字符串是否有效。
我根本没有测试过这个函数,但我能想到的唯一可能失败的情况是过多的括号:((5))。
递归的一种替代方法可以是某种词法解析,比如:
enum {
ExpectingLeftExpression,
ExpectingRightExpression,
ExpectingPlus,
ExpectingEnd,
} ParseState;
// returns true if str is valid
bool check(char* str) {
ParseState state = ExpectingLeftExpression;
do {
switch (state) {
case ExpectingLeftExpression:
if (*str == '(') {
} else if (*str >= '0' && *str <= '9') {
state = ExpectingPlus;
} else {
printf("Error: Expected left hand expression.");
return false;
}
break;
case ExpectingPlus:
if (*str == '+') {
state = ExpectingRightExpression;
} else {
printf("Error: Expected plus.");
return false;
}
break;
case ExpectingRightExpression:
if (*str == '(') {
state = ExpectingLeftExpression;
} else if (*str >= '0' && *str <= '9') {
state = ExpectingEnd;
} else {
printf("Error: Expected right hand expression.");
return false;
}
break;
}
} while (*(++str));
return true;
}
这个函数根本不完整,但你应该能够看到它的去向。无论如何,我认为递归在这种情况下效果更好。
相关文章:
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 类中的虚拟布尔函数参数不起作用
- 我无法在 c++ 中调用布尔函数(已关闭)
- 如何使用布尔函数按降序对数组进行排序?
- 在布尔函数 c++ 中使用 elses
- 布尔函数在一段时间内不起作用
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 如何编写正确的"布尔"函数?
- 无法在 c++ 中" xor() "命名布尔函数
- 递归布尔函数的问题
- 布尔函数始终返回真正的 C++
- 具有单个参数的布尔函数映射
- 返回类型布尔函数中的声明语法错误
- 为什么我的布尔函数返回 true 会导致读取访问冲突?
- 单调布尔函数
- 布尔函数无法返回真或假
- 在C 中调用布尔函数
- 模板布尔函数没有<>,这是什么意思?