My program will process the first and second line of the text file but gets a bit crazy after that. Lines 1, 2, 3, and 5 are supposed to match and line 4 does not. It gets lines 1 and 2 but 3 and 5 are incorrect and it processes a blank line. Not sure how to fix this. All help is greatly appreciated!

input:
()
[](){}
[{()}]
[[))
{()[()]}

output:
( ) 
Parenthesis matched

[ ] ( ) { } 
Parenthesis matched

[ { ( ) } ] 
Parenthesis Not matched

[ [ ) ) 
Parenthesis Not matched

{ ( ) [ ( ) ] } 
Parenthesis Not matched


Parenthesis matched


int main()
  {
    Stack stackLeft;
    char inputArray[20];
    char value;
    int inputCount = 0;
    int countLeft = 0;

    //Open inFile
    inFile.open("StackStr.txt");

    while(!inFile)
    {
        cout << "Error opening the inFile." << endl;
        return 1;
    }

    //Open outFile
    outFile.open("StackResults.txt");

    while(!outFile)
    {
        cout << "Error opening the outFile." << endl;
        return 1;
    }

    while(inFile)
    {
        countLeft = 0;

        inFile.getline(inputArray, 20,'\n');
        inputCount = 0;

        while(inputArray[inputCount]!='\0')
        {
            value = inputArray[inputCount];
            cout << value << " ";
            outFile << value << " ";
            inputCount++;

            if(value=='(' || value=='[' || value=='{')
            {
                stackLeft.push(value);
                countLeft++;
            }
            else if(value==')' || value==']' || value=='}')
            {
                if(stackLeft.top() == '(' && value == ')')
                {
                    stackLeft.pop();
                    countLeft--;
                }
                else if(stackLeft.top() == '[' && value == ']')
                {
                    stackLeft.pop();
                    countLeft--;
                }
                else if(stackLeft.top() == '{' && value == '}')
                {
                    stackLeft.pop();
                    countLeft--;
                }
            }
        }

        if(countLeft == 0)
        {
            cout<<endl<<"Parenthesis matched" << endl << endl;
            outFile<<endl<<"Parenthesis matched" << endl << endl;
        }
        else
        {
            cout<<endl<<"Parenthesis Not matched" << endl << endl;
            outFile<<endl<<"Parenthesis Not matched" << endl << endl;
        }
    }

    system("pause");
    return 0;
  }

try printing the new top of the stack and next input after every pop/push to have a general view of the problem and see if the current conditions would satisfy the current input and top of stack,

Edited 4 Years Ago by zeroliken

This question has already been answered. Start a new discussion instead.