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

Dani AI

Generated

Short summary of what went wrong and how to fix it (references: original code and ’s debugging suggestion).

There are three concrete problems visible in the posted code that explain the stray output and the incorrect results:

  • The outer loop uses the file-stream state instead of checking the result of getline, which can cause an extra iteration and a spurious "matched" print for a blank read.
  • The code calls the stack's top() without first checking whether the stack is empty; calling top() on an empty stack is undefined behavior and will produce unpredictable results.
  • Only the counter is reset between lines; the stack itself is not cleared, so leftover items from previous lines can wreck subsequent checks.

All three should be fixed. Use std::string with std::getline for the read loop, construct or clear a fresh stack for each input line, and always check empty() before using top()/pop(). ’s tip to print the stack top after pushes/pops is a good debugging step — it would have immediately shown an attempt to read top() from an empty stack.

Example (robust) approach:

#include <fstream>
#include <string>
#include <stack>

bool matches(char open, char close) {
  return (open=='(' && close==')') ||
         (open=='[' && close==']') ||
         (open=='{' && close=='}');
}

std::ifstream in("StackStr.txt");
std::ofstream out("StackResults.txt");
std::string line;
while (std::getline(in, line)) {
  std::stack<char> st;
  bool ok = true;
  for (char c : line) {
    if (c=='(' || c=='[' || c=='{') st.push(c);
    else if (c==')' || c==']' || c=='}') {
      if (st.empty() || !matches(st.top(), c)) { ok = false; break; }
      st.pop();
    }
  }
  if (!st.empty()) ok = false;
  out << line << '\n' << (ok ? "Parenthesis matched" : "Parenthesis Not matched") << "\n\n";
}

Notes: if you keep a custom Stack class, add an empty() method or a clear() routine and always check empty() before top(). Debug prints per are useful while verifying fixes.

Recommended Answers

All 2 Replies

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,

Thanks for the advice, I fixed it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.