I wrote the following code to judge whether an expression entered by user has correct sequence of brackets or not, e.g. if user enters [a*(b+c)] its ok. But if he enters [a*(b+c)[ its not correct.
Stacklist.cpp is a file which contains the linked list implementation of stacks and definitions of functions of push and pop. Display is the function which just shows the top entry.
#include<iostream>
#include<exception>
using namespace std;
#include"stacklist.cpp"
int main()
{
string s;
cin>>s;//user inputs the string
stacklist<int> stack1;//the class in stacklist.cpp...int because all bracket's ascii values are ints
char c;
while((c=cin.get())!=EOF)
{
switch('c')
{
case '(': case '{': case '[':
stack1.push('c');
break;
case ')':
{char s=stack1.display();
try
{
if(s=='(')
{ stack1.pop();
continue;}
else
throw 5;
}//try block
catch(5) //.......(a)
{
cout<<"unmatched bracket error";
exit(-1);
}//catch over
}//')' case
break;
case '}': //.......(b)
{char s=stack1.display();
try
{
if(s=='{')
{ stack1.pop();
continue;}
else
throw 6;
}//try block
catch(6) //......(a)
{
cout<<"unmatched bracket error";
exit(-1);
}//catch over
}//'}' case
break;
case ']': ........(c)
{char s=stack1.display();
try
{
if(s==']')
{ stack1.pop();
continue;}
else
throw 7;
}//try block
catch(7) //.............(a)
{
cout<<"unmatched bracket error";
exit(-1);
}//catch over
}//']' case
break;//..........(d)
default:
break;
} //switch
} //while
if(stack1.display==0)//0 is displayed if stack is empty
cout<<"string is correct"<<endl;
else
cout<<"unequal number of brackets"<<endl;
system("pause"); //........(e)
return 0;
} //main
Now the problem is that when I compiled the code there were various errors:
syntax error before numeric constant.........in all (a)
case label '}' not within switch statement........(b)
case label ']' not within switch statement........(c)
syntax error before break.................(d)
ISO forbids declaration of 'system' with no type...........(e)
Please tell me how to plug these errors?
systemis found in the headercstdio, but you did not#includethat header.Anyway, it’s best not to use “tricks” like
system("pause")to keep the console window after your program ends: if your console environment is not hanging around after your program has finished doing its meaningful work, then that’s your console environment’s fault/problem and you should configure it properly so that that does not happen. Pausing is not part of your program’s job.Catching looks like this:
object-nameis optional, butTypeis not.Therefore
catch (6)is ill-formed. The other errors are a result of this one: parsing of your program goes all wonky when you write stuff that is not valid C++!And your indentation is pretty horrendous.