Write a program to check for balancing symbols in the C++ language using stack.
ID: 3757358 • Letter: W
Question
Write a program to check for balancing symbols in the C++ language using stack. Consider /* */, (), [], {} symbols only. Your program should prompt the user for a file name that consist of C++ codes. To test, type simple code lines with comments and parenthesis in a text file, for instance,
void main()
{
/* Declaring array */
int ary[10];
for( int i=0;i<=10;i++)
ary[i] = i;
}
While testing miss closing the parenthesis and comments. Make sure that your program works for all cases.
Write an appropriate output message that resembles C++ compiler error messages, e.g Error at line 2, [ is not closed in the program
Explanation / Answer
#include <iostream>
#include <conio.h>
using namespace std;
struct node
{
char data;
node *next;
}*p = NULL, *top = NULL, *save = NULL,*ptr;
void push(char x)
{
p = new node;
p->data = x;
p->next = NULL;
if (top == NULL)
{
top = p;
}
else
{
save = top;
top = p;
p->next = save;
}
}
char pop()
{
if (top == NULL)
{
cout<<"underflow!!";
}
else
{
ptr = top;
top = top->next;
return(ptr->data);
delete ptr;
}
}
int main()
{
int i;
char c[30], a, y, z;
cout<<"enter the expression: ";
cin>>c;
for (i = 0; i < strlen(c); i++)
{
if ((c[i] == '(') || (c[i] == '{') || (c[i] == '['))
{
push(c[i]);
}
else
{
switch(c[i])
{
case ')':
a = pop();
if ((a == '{') || (a == '['))
{
cout<<"invalid expr!!";
getch();
}
break;
case '}':
y = pop();
if ((y == '[') || (y == '('))
{
cout<<"invalid expr!!";
getch();
}
break;
case ']':
z = pop();
if ((z == '{') || (z == '('))
{
cout<<"invalid expr!!";
getch();
}
break;
}
}
}
if (top == NULL)
{
cout<<"balanced expr!!";
}
else
{
cout<<"string is not valid.!!";
}
getch();
}
Output
enter the expression:
[{{{}}}{{()[[]]}}]
balanced expr!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.