2

CS クラスの C++ のスタック構造を使用して、特定の式の中括弧、大括弧、および括弧がすべて一致するかどうかをチェックするプログラムを実装することになっています。残念ながら、私は何かが一致しないと言い続けているので、これにはちょっと行き詰まっています。これが私がこれまでに得たものです:

#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;
}

スタック フレームワークは以前の演習から存在し、そこでは正常に機能していたので、エラーがあったとしても、void match

4

2 に答える 2

5
else
    cout << encountered << " has opened, but closing " << closing;
    cout << " encountered!\nParentheses do not match\n";

2 行目は常に印刷されます。そのはず

else
{
    cout << encountered << " has opened, but closing " << closing;
    cout << " encountered!\nParentheses do not match\n";
}

また

if (expected != encountered)
            closing = i;
            pass = false;

する必要があります

if (expected != encountered)
{
            closing = i;
            pass = false;
}

あなたはパイソン出身ですか?インデントは C++ のロジックには影響しません。読みやすさに影響するだけです。

于 2012-11-11T22:19:04.033 に答える
2

match 関数では、インデックスではなく、文字をテストする必要があります。

void match(char expr[])
{
...
    for (int i=0; pass && (i<strlen(expr)); i++)
    {
        char c = expr[i]; // use this c instead of i below!!!!!!!
        if ((c==40)||(c==91)||(c==123))
            push(c);
        else 
        {
            if (c==41)
                expected = 40;
            if (c==93)
                expected = 91;
            if (c==125)
...

また、プッシュでカウンターを更新しませんでした:

void push(int element)
{
...
   ++numElems; // Was missing!!!!
}
于 2012-11-11T23:23:33.400 に答える