求一个输入带括号的算术表达式,判断该表达式括号是否匹配的c++程序代码
时间: 2024-10-21 21:03:06 浏览: 41
在C++中,你可以使用栈数据结构来解决括号匹配的问题。这是一个简单的递归算法示例:
```cpp
#include <iostream>
#include <stack>
using namespace std;
// 判断括号是否匹配
bool isParenthesesMatch(string exp) {
stack<char> s;
for (char ch : exp) {
if (ch == '(') { // 如果遇到左括号,压入栈中
s.push(ch);
} else if (ch == ')') { // 遇到右括号
if (s.empty()) { // 如果栈为空,说明不匹配
return false;
}
char top = s.top(); // 获取栈顶元素
s.pop(); // 出栈
if (top != '(') { // 检查栈顶元素是否为对应的左括号
return false;
}
} else { // 对于非括号字符,直接跳过
continue;
}
}
// 如果遍历结束后栈不为空,说明有未匹配的左括号
return s.empty();
}
int main() {
string expression;
cout << "Enter an arithmetic expression with parentheses: ";
cin >> expression;
if (isParenthesesMatch(expression)) {
cout << "The parentheses are balanced.\n";
} else {
cout << "The parentheses are not balanced.\n";
}
return 0;
}
```
阅读全文
相关推荐


















