In: Computer Science
Using STL stack class, implement in C++ the following pseudocode function
checkBraces(aString: string) that checks for balanced braces { } in a given string /
arithmetic expressions. Write a main() program to test the function.
// Checks the string aString to verify that braces match.
// Returns true if aString contains matching braces, false otherwise.
checkBraces(aString: string): boolean{
aStack = a new empty stack
balancedSoFar = true
i =0
// Tracks character position in string
while (balancedSoFar and i < length of aString) {
ch = character at position i in aString i++
// Push an open brace
if (ch is a '{')
aStack.push('{')
// Close brace
else if (ch is a '}')
{ if (!aStack.isEmpty())
aStack.pop() // Pop a matching open brace
else
balancedSoFar = false
}
// No matching open brace // Ignore all characters other than braces
}
if (balancedSoFar and aStack.isEmpty())
aString has balanced braces else
aString does not have balanced braces
}
#include
#include
using namespace std;
//required function to check balanced braces
//acc to pseudocode
bool checkBraces(string aString){
stack
bool balancedSoFar = true;
int i = 0;
while(balancedSoFar && i < aString.size()){
char ch = aString[i];
i++;
if(ch == '{'){
aStack.push(ch);
}
else if(ch == '}'){
if(!aStack.empty()){
aStack.pop();
}
else balancedSoFar = false;
}
}
if(balancedSoFar && aStack.empty()){
return true;
}
else return false;
}
int main(){
string aString;
cout << "Enter the string to check for matching braces: ";
cin >> aString;
if(checkBraces(aString))cout << "balanced braces" << endl;
else cout << "unbalanced braces" << endl;
}
Sample IO: