c++ - How to handle the exception, when stack is empty(character element of string accesses an empty stack)? - Stack Overflow

I have problem with my program on C++, witch checks an valid brackets.If i want to check ')'

I have problem with my program on C++, witch checks an valid brackets. If i want to check ')', i get segmentation error.

Example:

input: (()) output: Yes

input: (() output: No

input: ()) output: back() called an empty deque(Visual C++)

As i understand it, element of string trying to access an empty stack. How to handle this case?

My code

#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool valid_brackets(string& expression)
{
    stack<char> brackets;
    for (char c : expression)
    {
        if (c == '(')
            brackets.push(c);
        else if (c == ')')
        {
            if (c == ')' && brackets.top() != '(')
                return false;
            brackets.pop();
        }

    }
    return brackets.empty();
}
int main()
{
    string expression;
    getline(cin, expression);
    if (valid_brackets(expression))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745118972a4612301.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信