weixin_39115868 2018-04-07 06:41 采纳率: 33.3%
浏览 1287
已结题

代码没有问题,运行时却出错,为什么会这样呢

#include
#include
#include
using namespace std;
#define MAXSIZE 100

typedef struct {
char data[MAXSIZE];
int top;
}stack;

//初始化栈
void Initstack(stack *s){
s->top = -1; //将栈的栈顶指针置为-1,表示栈为空
printf("栈初始化成功\n");
}

//进栈函数
int push(stack *s,char x){
if(s->top >= MAXSIZE - 1){
printf("栈满,无法进栈\n");
return 0; //栈满,上溢
}
else{
s->top++;
s->data[s->top] = x;
printf("已经进栈\n");
return 1;
}
}

//出栈算法
int pop(stack *s,char e){
if(s->top < 0){
printf("栈中已空,无元素可出栈\n");
return 0; //栈空,下溢
}
else{
e = s->data[s->top];
s->top--;
printf("已经出栈\n");
return 1;
}
}

//取栈顶元素算法
char GetTop(stack *s,char e){
if(s->top < 0){
printf("栈为空,无元素可取\n");
return 0; //栈空,没有元素可取
}
else{
printf("将栈顶元素取到e中\n");
e = s->data[s->top];
return e;
}
}

//判断栈空算法
int empty(stack *s){
if(s->top < 0){
printf("栈为空\n");
return 1; //栈空,返回值为1和栈为空
}
else{
printf("栈不为空\n");
return 0; //栈不是空的
}
}

int matching(char *exp,stack *s,int i){
int k = 0,state = 1;
char e;
while (k < i) {
switch (exp[k]){
case '(':{
push(s,exp[k]); k++;
break;
}
case ')': {
if(empty(s) == 0){
if(GetTop(s,e) == '('){
pop(s,e);
k++;
}
else{
printf("与前一个元素不匹配\n");
state = 0;
}
}
else{
state = 0;
}
break;
}
case '[':{
push(s,exp[k]);k++;
break;
}
case ']':{
if(empty(s) == 0){
if(GetTop(s,e) == '['){
pop(s,e);
k++;
}
else{
printf("与前一个元素不匹配\n");
state = 0;
}
}
else{
state = 0;
}
break;
}
case '{':{
push(s,exp[k]);k++;
break;
}
case '}':{
if(empty(s) == 0){
if(GetTop(s,e) == '{'){
pop(s,e);
k++;
}
else{
printf("与前一个元素不匹配\n");
state = 0;
}
}
else{
state = 0;
}
break;
}
default:{
return 2;
}
}
if(state == 0){
return 0;
}
}
return 1;
}

int main(){
char str[100];
stack *sqstack;
int i = 0;
printf("请输入一组要验证的括号\n");
scanf("%s",str);
for(i = 0;str[i] != '\0';i++){
}
printf("%d\n",i);
Initstack(sqstack); //初始化栈
int x = matching(str,sqstack,i);
if(x == 1){
printf("括号匹配\n");
}
else if(x == 0){
printf("括号不匹配\n");
}
else{
printf("输入内容不是括号\n");
}

return 0;
}

  • 写回答

3条回答

  • 默陌叶 2018-04-08 01:53
    关注

    逻辑挺清晰,看起来没问题,可以考虑编码的问题。可能c++文件用的utf8编码,输入的字符用的gbk之类的,导致判断字条相等出错。这是一个思路,仅供参考。

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?