I'm trying to implement a stack to check if a file has balanced (), [], and {}. The program is supposed to take in a file and check if it is balanced and return a boolean. When I run the program it only works for the last parentheses in the file. How can I change the code to make it work for parentheses before the last pair. The input file is just a simple c file.
Side question:
If I wanted to make this program work with an html file do I just have to change (), [], {} with the html tags?
This is the code I have
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
bool balanced(string A[], int n)
{
int i;
stack <string> a;
for (i = 0; i < n; i++) {
if (A[i] == "(" || A[i] == "{" || A[i] == "["){
a.push(A[i]);
} else
if (A[i] == ")" || A[i] == "}" || A[i] == "]") {
if (a.empty()) {
return false;
} else {
a.pop();
return true;
}
}
}
}
int main()
{
ifstream infile;
infile.open ("Text.txt");
string A[1000];
int i = 0;
int n = (sizeof(A) / sizeof(*A));
while (!infile.eof()) {
getline(infile, A[i], '\n');
i++;
}
bool out;
out = balanced(A, n);
if (out == true) {
cout << "legal";
} else {
cout << "illegal";
}
return 0;
}