c++ Program needs to compile in an linux environment with g++ compiler. As part
ID: 656177 • Letter: C
Question
c++
Program needs to compile in an linux environment with g++ compiler.
As part of our studies of Abstract Data Types, we will be using a stack to solve a problem.
Given an equation such as: ([1+3]-42/(4*4)) your task is to determine if the parenthesis and braces match. If they do, the ouput of the program will be "equation ok". If the equation has a problem, your output will reflect the error. For example: ((a+b+) would result in "missing )" .
You can ignore the actual equation and just focus on the parenthesis and brackets.
We will be using the Stack provided by the Standard Template Library (STL)
Input to program - Put the test expressions in a file (for example, "exp.dat") one expression per line and then get the file name from the command line.
if the file exp.dat contained:
((a+b)-6
[(hey)-9]
linux prompt > ./check exp.dat
((a+b)-6 === missing )
[(hey)-9] === valid expression
Explanation / Answer
// checkexpression.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "fstream"
#include "iostream"
#include "string"
using namespace std;
char miss;
bool checkparenthesis(string line)
{
int cnt1=0;
for(int i=0;i<line.length;i++)
{
if(line.substr(i,1) == "(")
cnt1++;
if(line.substr(i,1) == ")")
cnt1--;
if (cnt1 < 0)
{
miss=')';
break;
}
}
if (cnt1 == 0)
{
for(int i=0;i<line.length;i++)
{
if(line.substr(i,1) == "{")
cnt1++;
if(line.substr(i,1) == "}")
cnt1--;
if (cnt1 < 0)
{
miss='}';
break;
}
}
}
if (cnt1 == 0)
{
for(int i=0;i<line.length;i++)
{
if(line.substr(i,1) == "[")
cnt1++;
if(line.substr(i,1) == "]")
cnt1--;
if (cnt1 < 0)
{
miss=']';
break;
}
}
}
if (cnt1==0)
return true;
else
return false;
}
int main(int argc, char* argv[])
{
ifstream file(argv[0]);
if (!file.is_open())
cout << "File could not be opened!!!";
else
{
string strline;
while(!file.eof())
{
getline(file,strline);
if (checkparenthesis(strline) == true)
cout << strline << " === " << " valid expression ";
else
cout << strline << " === " << " missing " << miss;
}
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.