Click here to Skip to main content
15,400,388 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
C++
#include<iostream>
#include<stack>
using namespace std ;
bool areBracketsBalanced(string expr) 
{
stack<char> s;
char x;
for (int i = 0; i < expr.length(); i++) 
{
    if (expr[i] == '(' || expr[i] '['== 
    ||expr[i] )'{' ==
    { 
    s.push(expr[i]); 
    continue;
}
if (s.empty()) 
return false ;
switch (expr[i])
{ 
case :')'
x = s.top(); 
    s.pop(); 
    if (x == '{' || x )'[' ==
return false ;
break ;
case :'}'
x = s.top();
s.pop();
if (x == '(' || x )'[' == 
return false ;
break ;
case :']'
x = s.top();
s.pop();
if (x == '(' || x )'{' == 
return false ;
break ;
} }
return (s.empty()) ;
} 
int main()
{
    int inc = 1; 
    string expr1 ;
    string expr2 ;
cout << "sample run :" << inc << "\n ";
cout << "Enter an expresion :"; 
cin >> expr1;
if (areBracketsBalanced(expr1))
cout << "output:The expresion is Balanced\n"; 
else
cout << "output:The expresion is not Balanced\n";
cout << "-------------------------------------\n "; 
inc ++;
cout << "sample run :" << inc << "\n ";
cout << "Enter an expresion :";
cin >> expr2; 
if (areBracketsBalanced(expr2)) 
cout << "output:The expresion is Balanced\n";
else
cout << "output:The expresion is not Balanced\n";
cout << "-------------------------------------\n "; 
return 0 ;
}


What I have tried:

I tried many solutions and watched tutorials but I don't know how to debug this code.
Posted
Updated 26-Oct-21 11:40am
v2
Comments
Patrice T 24-Oct-21 9:46am
   
And you plan to describe the error ?
Member 15376207 24-Oct-21 9:52am
   
Sorry, I don't understand what do you mean?🤍
Richard MacCutchan 24-Oct-21 10:04am
   
He means: what are the errors, and which lines do they occur on? You need to provide full details of your problem.
Member 15376207 24-Oct-21 9:54am
   
I'm so sorry my English isn't very good but if I wasn't desperate I wouldn't ask the question after days of trying to solve it.

The formatting of your code became fouled up. Here is what I think it should be :
C++
bool areBracketsBalanced( std::string expr )
{
    std::stack<char> s;
    char x;
    for( int i = 0; i < expr.length(); i++ ) 
    {
        if( expr[i] == '(' || expr[i] == '[' || expr[i] == '{' )
        { 
            s.push( expr[i] );
            continue;
        }

        if( s.empty() )
            return false;

        switch( expr[i] )
        {
        case ')' :
            x = s.top(); 
            s.pop(); 
            if( x == '{' || x == '[' )
                return false;
            break;
        case '}' :
            x = s.top();
            s.pop();
            if( x == '(' || x == '[' )
                return false;
            break;
        case ']' :
            x = s.top();
            s.pop();
            if( x == '(' || x == '{' )
                return false;
            break;
        }
    }
    return s.empty();
}
I have not corrected anything there. I just moved parenthesis and colons around.
   
Try this and try to really understand the differences to your coce

bool areBracketsBalanced(string expr)
{
   stack <char> s;
   for (int i = 0; i < expr.length(); i++)
   {
      // Take the current character we need to process
      char current = expr[i];
      if (current == '(' || current == '[' || current == '{')
      {
         // It is an opening bracket. Push it onto the stack ...
         s.push(current);
         
         // ... and go on with the next input character
         continue;
      }

      // Maybe it is a kind of closing bracket
      char stackNeedToBe;
      switch (current)
      {
         case ')':
            stackNeedToBe = '(';
            break;
         case '}':
            stackNeedToBe = '{';
            break;
         case ']':
            stackNeedToBe = '[';
            break;
         // No closing bracket, so we are done
         default: continue;
      }

      // We are done when stack ist empty
      if (s.empty()) return false;

      // Does the closing bracket match the opening bracket on the stack?
      char stackTop = s.top();
      s.pop();

      // In case it does not match we are done
      if (stackTop != stackNeedToBe) return false;
   }
   return (s.empty());
}


Additional comment
About 20+ years I avoided from using 'continue' and implementing multiple 'return' in a method. Which you maybe can imaging lead to nasty nested 'if' statements.
Meanwhile I changed my mind and came to the conlucsion: Take the appropriate action at the time you realize it is needed.
a.) 'continue'
It perfectly shows we are done at the time you write the statment. Means, we do not need to check what's happens after that statement. We simply can concentrate to go with the next loop.
b.) 'return'
Similar like a.).
   
v3
Comments
Dave Kreskowiak 24-Oct-21 12:05pm
   
Doing it for the OP is not helping the OP.

You just took away the opportunity to learn the critical skills of debugging.
[no name] 24-Oct-21 12:08pm
   
I agree. But I hope some implementation style of mine will help him
Rick York 27-Oct-21 20:22pm
   
It is easy to cause problems like memory leaks with multiple return statements but if you always use automatic objects it is not an issue. Things like unique_ptr and vectors are very useful for preventing leaks. I use Visual Studio's tools for memory tracking and they are pretty good. I wrote this tip on the topic : https://www.codeproject.com/Tips/5284084/Memory-Allocation-Tracking-for-Cplusplus-Code
Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

And we have no idea what the code is indented to do, much less what it does that you didn't expect, or didn't do that you did!

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C#
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is. But do yourself a favour first: indent your code, and add { and } even for single line blocks - it makes your code more readable and easier to follow as well as more reliable in the long run.!

This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!

If you don't know how to use a debugger, google for the name of you IDE ("Visual Studio" perhaps) and "C++ debugger" and you should find usage instructions.
   
Comments
[no name] 24-Oct-21 11:27am
   
And because the presented code does not even compile, your answer probably confuse the OP even more ;)
CPallini 25-Oct-21 2:13am
   
Well, he is NOT the same guy that commented your post...
There's nothing to debug because the code doesn't compile. 'debug' means running and analyzing the compiled program, but you do not have a program yet.

The compiler fails to create the program for you. It tells you so and gives you an error message, or more likely multiple error messages. These messages tell you:
(a) where the compiler found the error (file name and line of the bad code)
(b) sometimes a name or code segment that it doesn't understand
(c) an error code (typically a letter followed by a number, e. g. C4011)
(d) a short text describing this error
(e) sometimes a bit of context that the compiler took when trying to interpret your code

Regarding (a), the compiler sometimes fails after the point where the actual error is, so when you check the position in the code that hthe compiler indicates, and don't spot anything wrong, go up a line or two and check if the error is there.

Regarding (c), you can do an internet search for this error code to find a lot more information on errors of this type, as well as examples from other people who had this error, and how they solved it. This is normally more than enough information to solve such errors.

If you cannot spot and correct the error from (a) and (c) as described above, you should provide the full information that your compiler printed on the error to anyone who is trying to help. This will greatly simplify the effort of finding and fixing the error for others looking at your code!
   
std :: string :: size () returns the type size_t, which is unsigned. I get warning C4018: '<': signed/unsigned mismatch in your solution here.

If you use containers, you can code shorter and avoid type problems at the same time.
C++
bool areBracketsBalanced(std::string expr)
{
	std::stack<char> s;
	char x;

	for (auto i : expr) // access each value
	// for (int i = 0; i < expr.length(); i++)
	{
		if (i == '(' || i == '[' || i == '{')
		// if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{')
		{
		s.push(i);
		continue;
		}

		if (s.empty())
			return false;

		switch (i)
		// switch (expr[i])
		{
		case ')': ...
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900