im trying to write a code using stack container(templated) where my program would have to read string one character at a time, and a algorithm that can compare parenthesis. this is what i need to read
1. A + B - C
2. A * B / (C +10)
3. A * ((B / C) + D + (E - 10)
4. A * (B / C) + D + (E - 10))
#include <fstream>
#include <iostream>
#include <string>
usingnamespace std;
// tests if the brackets in the coming line of the input stream match.
bool doBracketsMatch( istream & is )
{
int nOpenBrackets = 0;
while ( is.good() ) // as long as there are characters to read...
{
switch ( is.get() ) // get character from input stream
{
case'(': ++nOpenBrackets; break; // increase open brackets
case')': --nOpenBrackets; break; // decrease open brackets
case'\n': return nOpenBrackets == 0; // at line end: check if all brackets are closed
}
// check, if there are not more closing brackets than opening ones.
if ( nOpenBrackets < 0 )
{
// read characters to the end of the line and return.
while ( is.good() )
if ( is.get() == '\n' )
returnfalse;
}
}
return nOpenBrackets == 0;
}
int main(void)
{
// Get filename from user.
cout << "Enter the name of an existing text file: ";
string s;
cin >> s;
// open file
ifstream is( s.c_str() );
// show result
for (int line = 1; is.good(); ++line )
{
constbool match = doBracketsMatch( is );
cout << "The brackets in line " << line
<< ( match ? " match." : " don't match." )
<< endl;
}
}
string:A + B - C no parenthesis
string: A * B / (C +10) matching parenthesis
string: A * ((B / C) + D + (E - 10) parenthesis dont match. missing right parenthesis
string: A * (B / C) + D + (E - 10)) parenthesis dont match. missing left parenthesis
PS: why did you write the function void as a parameter of the function int main()????
by the way, why did you use "int argc; char** argv" as a parameter of function main???
They allow you to read arguments passed from the command line. So you could execute a program like this: ./ProgramName Arg1 Arg2 Arg3 ...
It's a good habit to do even if you will never read the arguments, as you will always be able to without having to go back and add it later. Char** argv is the same as char *argv[].