(1)pop函数第二个参数需要用引用或者指针,否则无法返回e的值。如下:
void pop(stack& a, char& e) //这里用引用,e前面加&符号
{
a.top--;
e = *a.top;
}
(2)再第一个if语句中,不应该是pop,应该是push
完整代码如下(修改部分有注释):
#include <iostream>
#include <string>
using namespace std;
struct stack
{
char* base;
char* top;
};
void init(stack& a)
{
a.base = new char[100];
a.top = a.base;
}
void push(stack& a, char e)
{
*a.top = e;
a.top++;
}
void pop(stack& a, char& e) //修改1 e用引用,前面加&
{
a.top--;
e = *a.top;
}
int main()
{
stack s;
init(s);
string str;
getline(cin, str);
char ch[200] = { '\0' };
strcpy(ch, str.c_str());
int i = 0;
bool flag = true;
char tmp;
for (i = 0; i < strlen(ch); i++)
{
if (ch[i] == '{' || ch[i] == '[' || ch[i] == '(')
push(s, ch[i]); //修改2,这里是push,不是pop
if (ch[i] == '}')
{
pop(s, tmp);
if (tmp != '{')
{
flag = false;
break;
}
}
else if (ch[i] == ')')
{
pop(s, tmp);
if (tmp != '(')
{
flag = false;
break;
}
}
else if (ch[i] == ']')
{
pop(s, tmp);
if (tmp != '[')
{
flag = false;
break;
}
}
}
if (flag == true) cout << "yes";
else cout << "no";
return 0;
}
这应该是push吧