|
|
发表于 2011-10-14 00:06:20
|
显示全部楼层
不好意思,我发现了这个代码问题很多,不仅仅是你说的那个问题,现在把它改好了,你看看这个吧,前面我发的你就别看了,如果你的意思是判断括号是否匹配的话这个代码基本上还算正确。。。
#include<iostream>
#include<stack>
#include<string>
#include <stdlib.h>
using namespace std;
int main()
{
stack<char> sexp;//处理表达式的stack对象
string exp;//读入表达式
cout<<"Enter a expression:"<<endl;
cin>>exp; //处理表达式
string::iterator iter = exp.begin();
while(iter!=exp.end())
{
if(*iter !=')')//读到的字符不是右圆括号
{
sexp.push(*iter);
}
else
{
//读到的字符是右圆括号,弹出元素,直到栈顶为左圆括号或栈为空
while(!sexp.empty() && sexp.top()!='(' )
{
sexp.pop();
}
if(sexp.empty())//栈为空
{
cout<<"parenthese are not matched "<<endl;
exit(0);
}
sexp.pop();
}
++iter;
}
while(!sexp.empty() && sexp.top()!='(' )
{
sexp.pop();
}
if(sexp.top()=='(')
cout<<"parenthese are not matched"<<endl;
else
cout<<"paraenthese are mathed"<<endl;
return 0;
}
|
|