标题:括号匹配的检验问题大家帮我看看
只看楼主
ec_月月
Rank: 1
等 级:新手上路
帖 子:10
专家分:0
注 册:2008-10-8
 问题点数:0 回复次数:0 
括号匹配的检验问题大家帮我看看
[bo]不知道为什么不管输入正确或错误的表达式运行结果都是括号不匹配!我写的代码帮我看看哪里错了,先谢谢了[/bo]

#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
#include<conio.h>
#include<process.h>

#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100;
#define STACKINCREMENT 10;

typedef int Status;
typedef char sElemType;
typedef int Boolean;

typedef struct{
    sElemType *base;
    sElemType *top;
    int stacksize;
}SqStack;

Status InitStack(SqStack &S)
{
    S.base = (sElemType *)malloc(100 * sizeof(sElemType));
    if(!S.base) exit(OVERFLOW);
    S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
    return OK;
}

Status StackEmpty(SqStack &S)
{
    if(S.top==S.base)
        return TURE;
    else
        return FALSE;
}

Status GetTop(SqStack S, sElemType &e)
{
    if(S.top == S.base) return ERROR;
    e = * (S.top - 1);
    return OK;
}

Status Push(SqStack &S, sElemType e)
{
    if(S.top - S.base >= S.stacksize)
    {
        S.base = (sElemType *)realloc(S.base,(S.stacksize + 10) * sizeof(sElemType));
        if(!S.base)   exit(OVERFLOW);
        S.top = S.base + S.stacksize;
        S.stacksize += STACKINCREMENT;
    }
       *S.top++ = e;
        return OK;
}

Status Pop(SqStack &S, sElemType &e)
{
    if(S.top = S.base)   return ERROR;
    e = * --S.top;
    return OK;
}

void check()
{
    SqStack S;
    InitStack(S);
    sElemType ch[50];
    sElemType *p,e;
    gets(ch);
    p = ch;   //要习惯用工作指针
    while(*p)
    
        switch(*p)
        {
        case '(':  
        case '[':   
        case '{': Push(S,*p++);  //左括号入栈同时q++
            break;
        case ')':
        case ']':
        case '}': if(!StackEmpty(S))
                  {
                      Pop(S,e);
                      if(!(e=='('&&*p==')'||e=='['&&*p==']'||e=='{'&&*p=='}'))
                          cout<<"括号不匹配!"<<endl;
                      exit(ERROR);
                  }
                 else
                 {
                      cout<<"缺少左括号!"<<endl;
                      exit(ERROR);
                 }
                 break;
        default: p++;
        }
    if(StackEmpty(S))
        cout<<"括号匹配!"<<endl;
    else
        cout<<"缺少右括号!"<<endl;
}

void main()
{
    cout<<"请输入带括号的表达式:"<<endl;
    check();
}
搜索更多相关主题的帖子: 括号 检验 
2008-10-12 11:47



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-237761-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015451 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved