最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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;
}
发布评论

评论列表(0)

  1. 暂无评论