【发布时间】:2012-03-15 07:35:23
【问题描述】:
有效表达式 = 一位数
与
有效表达式 = (有效表达式 + 有效表达式)
这意味着我尝试创建的布尔函数将只接受以下类型的表达式作为有效表达式:
5
(5+3)
(6+(3+2))
((7+1)+(5+1))
............... etc.
我希望我的函数参数保持原样(istringstream& 是),并且我想在我的函数中使用 get(ch)。
我也想递归地做。但是,我做错了,它只验证类型的表达式:single digit
我的递归问题出在哪里?而且我知道它甚至不是一个适当的递归,我确信一个适当的递归甚至可以在更少的行中完成这项工作并且没有嵌套的 ifs..
感谢您提供任何有用的建议!
#include <iostream>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
bool isvalid(istringstream& is)
{
char ch;
is.get(ch);
if(ch-'0'>=0 || ch-'0'<=9) return true;
if(ch=='(' && isvalid(is))
{
is.get(ch);
if(ch=='+' && isvalid(is))
{
is.get(ch);
if(ch==')') return true;
}
}
return false;
}
bool empty(istringstream& is)
{
char ch;
is.get(ch);
return is.fail();
}
int main()
{
string s;
while(getline(cin,s))
{
istringstream is(s);
cout<<(isvalid(is) && empty(is) ? "Expression OK" : "Not OK")<<endl;
}
}
【问题讨论】:
标签: c++ function recursion boolean