使用C++匹配括号,大括号和括号

Axi*_*xim 2 c++

我们应该实现一个程序来检查给定表达式中的大括号,括号和parens是否都使用C++中的堆栈结构匹配我的CS类.不幸的是,我有点坚持这个,因为我一直告诉我一些不匹配的东西,即使最明确的确实如此.这是我到目前为止所得到的:

#include <stdlib.h>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

struct cell {int value; cell* next; };
cell* top;
int numElem;

void init()
{
    top = NULL;
    numElem = 0;
}

int pop()
{
    int res;
    if (top != NULL)
    {
        res = top -> value;
        top = top -> next;
        numElem--;
    } else {
        cout << "FAIL: Stack empty!\n";
        res = -1;
    }
    return res;
}

void push(int element)
{
    cell* cat = new cell;
    cat -> value = element;
    cat -> next = top;
    top = cat;
}

void match(char expr[])
{
    bool pass = true;
    char expected;
    char encountered;
    char closing;
    for (int i=0; pass && (i<strlen(expr)); i++)
    {
        if ((i==40)||(i==91)||(i==123))
            push(i);
        else 
        {
            if (i==41)
                expected = 40;
            if (i==93)
                expected = 91;
            if (i==125)
                expected = 123;
            encountered = pop();
            if (expected != encountered)
                closing = i;
                pass = false;
        }
    }
    if (pass)
        cout << "Parentheses match OK!\n";
    else
        cout << encountered << " has opened, but closing " << closing;
        cout << " encountered!\nParentheses do not match\n";
}

int main(int argc, char * argv[])
{
    init();
    match(argv[1]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于堆栈框架存在于上一个练习并在那里工作正常,我强烈假设应该有任何错误 void match

Luc*_*ore 5

else
    cout << encountered << " has opened, but closing " << closing;
    cout << " encountered!\nParentheses do not match\n";
Run Code Online (Sandbox Code Playgroud)

第二行总是打印.它应该是

else
{
    cout << encountered << " has opened, but closing " << closing;
    cout << " encountered!\nParentheses do not match\n";
}
Run Code Online (Sandbox Code Playgroud)

if (expected != encountered)
            closing = i;
            pass = false;
Run Code Online (Sandbox Code Playgroud)

也应该是

if (expected != encountered)
{
            closing = i;
            pass = false;
}
Run Code Online (Sandbox Code Playgroud)

你来自蟒蛇吗?缩进不会影响C++中的逻辑,只会影响可读性.

  • 这就是为什么你总是**总是**在代码块周围使用大括号. (3认同)