This program is supposed to check whether the parentheses are balanced (open and closing). The program runs, but returns valid
for all user input.
#ifndef _STACKLSAB_H_
#define _STACKSLAB_H_
#include <stack>
#include <string>
#include <vector>
#include "namevaluepair.h"
using namespace std;
class Stacks
{
public:
bool balanced(string exp);
bool match(char open, char closed);
private:
string st_PostData;
};
#endif
stacksLab.cpp (my program works in repl.it but doesn't with cgi):
#include <iostream>
#include <sstream>
#include "stacksLab.h"
#include <stack>
using namespace std;
bool Stacks::match(char open,char closed)
{
if(open == '(' && closed == ')') return true;
else if(open == '{' && closed == '}') return true;
else if(open == '[' && closed == ']') return true;
return false;
}
bool Stacks::balanced(string exp)
{
stack<char> S;
for(int i = 0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !match(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty();
}
main.cpp
#include <iostream>
#include "stacksLab.h"
#include <stack>
using namespace std;
int main()
{
/// complete the http header
cout << "Content-type: text/html\n\n";
Stacks st;
string expression;
cin>>expression;
if(st.balanced(expression))
cout<<"Valid\n";
else
cout<<"Not Valid\n";
}
I think this is the reason my program will not return correctly but not sure which way to go.
<form action="runme.cgi" method="POST">
<table align="center" bgcolor="antiquewhite">
<tr>
<td align="right">Enter parentheses here:</td>
<td><input type="text" name="parentheses "/> </td>
</tr>
<tr>
<td align="right"><input type="submit" /></td>
</tr>
</table>
</form>