I’ve been asked as a bonus programming challenge to see if braces match in a random string or char like this: {1+1} this would return 1, while {1+1}) would return 0.
This is what I have so far but it doesn’t seem to do anything. Any help would be great? thanks
//bonus.cpp
#include <iostream>
#include <string>
#include <queue>
#include <stack>
using namespace std;
int checkBraces (string s)
{
//int myLength = s.length();
std::stack<int> stack;
char d;
for (int i = 0; i < s.length(); i++)
{
char c = s[i];
if (c == '(')
{
stack.push(c);
}
else if (c == '[')
{
stack.push(c);
}
else if (c == '{')
{
stack.push(c);
}
else if (c == ')')
{
if (stack.empty())
{
return false;
}
else
{
d = stack.top();
stack.pop();
if (d != '(')
{
return false;
}
}
}
else if (c == ']')
{
if (stack.empty())
{
return false;
}
else
{
d = stack.top();
stack.pop();
if (d != '[')
{
return false;
}
}
}
else if (c == '}')
{
if (stack.empty())
{
return false;
}
else
{
d = stack.top();
stack.pop();
if (d != '{')
{
return false;
}
}
}
}
if (stack.empty()) return true;
else return false;
}
int main()
{
cout << "This program checks brace ([{}]) matching in a string." << endl;
checkBraces ("{1+1}");
}
It does do something. It prints
This program checks brace ([{}]) matching in a string..You are calling
checkBraces ("{1+1}")but you aren’t doing anything with the returned value. Since this call can be optimized away, you are in a sense correct that your program doesn’t seem to do anything.So make it do something. Print the string that is to be tested, then print the result of the test. Once you have done that, you should test, and when you’re done with that, you should test some more. Don’t just test easy cases such as
{i+1}. Test convoluted cases that should pass, and also test cases that should fail.Learning how to test and learning how to debug are just as important skills (if not more important skills) as is learning how to write code.