Question

I'm trying to write a program that will validate a user input consisting of brackets for proper nesting using a stack. I am trying to do this without the use of STL containers or recursion. I have somewhat hit a road block and I'm looking for a little nudge in the right direction. I think I am kind of close, but I feel like I may be oversimplifying it (I'm in the process of learning through self teaching)

Here is what I have so far:

#include <iostream>
#include <string>
#include "ArrayStack.h"
using namespace std;

bool test(char *argg);

int main()
{
    string input;
    int size = 50;

    cout << "enter here: ";
    getline(cin, input);
    for (int i = 0; i < size; i++)
        test(input[i]);
}

bool test(char *argg)
{
    ArrayStack S;
    char D;
    while ( *argg ) {
        switch( *argg ) {

            case '[': case '{': case '(':
                S.push( *argg );
                break;

            case ']':
                if( S.isEmpty() )
                    return false;
                D = S.pop();
                if( D!='[' )
                    return false;
                break;

            case '}':
                if( S.isEmpty() )
                    return false;
                D = S.pop();
                if( D!='{' )
                    return false;
                break;

            case ')':
                if( S.isEmpty() )
                    return false;
                D = S.pop();
                if( D!='(' )
                   return false;
                break;

            default:
                return false;
        }// end switch
                   argg++;
    }// end while

    return S.isEmpty(); // return true if reach here with empty stack

}

Thanks for any assistance in advance

Was it helpful?

Solution

If anything, you're overcomplicating it

char inverse(char c){
   if(c==']') return '[';
   if(c=='}') return '{';
   if(c==')') return '('; 
   return c;
}
int stillvalid(char c, ArrayStack &stack){
   if(strchr("[{(", c))
        stack.push(c);
    else if(strchr("]})", c))
        if(stack.isEmpty() || inverse(c) != stack.pop())
            return 0;
    return 1;
}

int main(){
    int c;
    ArrayStack stack;
    while((c=getchar())!=EOF){
       if(!stillvalid((char)c, stack)){
           printf("bad\n");
           exit(0);
       }
    }
    printf("good\n");
    return 0;
}

Should be all you need.

OTHER TIPS

Trace through your code by hand with the input myfunc(42);

Observe what happens, character by character. That should point you your errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top