balancing brackets crashing

I cant get this balancing brackets program to work, The problem I have is it keeps crashing when i try to open a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 #include <iostream>
#include <fstream>
#include <istream>
#include <stack>
#include<iostream>
#define SIZE 500
using namespace std;

int main ()
{
stack <char> S;
char a[SIZE]= "0";
char x;
int i,check=1;  
ifstream file;        
file.open("check.txt");   //opening the file

  do
  { 
   file.getline(a, SIZE);  //reading file line by line
   for(i=0;i<=SIZE;i++)
   {
    x=a[i];
    if(x=='[' || x=='(' || x=='{')
     S.push(x);
    else if(x== '/')
    {
     S.push(x);
     x=a[++i];
     if(x== '*')
      S.push(x);
     else
     {
      check = 0;
      goto end;
     }
    }
    else if(x==']' && S.top()=='[' || x==')' && S.top()=='(' || x=='}' && S.top()=='{' )
     S.pop();
    else if ( S.top()=='*' && x=='*')
    {
     S.pop();
     x=a[++i];
     if(S.top()=='/' && x=='/')
      S.pop();
     else
     {
      check=0;
      goto end;
     }
    }
    else if(S.empty() && (x==']' || x==')' || x=='}' || x=='*'))
    {
     check=0;
     goto end;
    }
    else if(x==']' && S.top()!='[' || x==')' && S.top()!='(' || x=='}' && S.top()!='{' )
    {
     check = 0;
     goto end;
    }
    a[i]= 0;
   }
   }while(!file.eof());
   
   end:
 if(check==0)
  cout<<"Brackets are not balanced."<<endl;
 else
  cout<<"Brackets are balanced."<<endl;
 return 0;
}
Last edited on
closed account (Dy7SLyTq)
a) you included iostream twice

sorry i cant be any more help than that. i havent used stack ever and i dont use c style searching
I think you should reexamine the control flow in your program (all those gotos are a red flag). If I understand correctly, you may "open" some sort of bracketed scope with (, [, or { and close it with ), ], or }, respectively. Your loop should be along the lines of:
foreach char in my input string
(i.e. until the current char is '\0'; your current loop goes the full length of your string buffer regardless of how long the user input is)

    if the current character opens a scope
        push it onto the stack
    if the current character closes a scope
        make sure it is symmetric to the scope opener on top of the stack
        if it does match, pop the stack
        else brackets are mismatched

Get that to work first, then you can begin considering the /* */ tokens.

EDIT: The way I've introduced here assumes the rule that a scope-closing token must correspond to the innermost open scope:
([])
is legal but
([)]
is not.
Last edited on
Topic archived. No new replies allowed.