0% found this document useful (0 votes)
56 views

Check Brackets in Code

This C++ program uses a stack to check for matching brackets in a string. It iterates through each character, pushing opening brackets to the stack and popping elements to check for closing bracket matches. If a closing bracket does not match the top of the stack or the stack is empty when a closing bracket is encountered, the position of the error is returned. Otherwise, "Success" is returned if all brackets are properly balanced.

Uploaded by

Bhubaneswar Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Check Brackets in Code

This C++ program uses a stack to check for matching brackets in a string. It iterates through each character, pushing opening brackets to the stack and popping elements to check for closing bracket matches. If a closing bracket does not match the top of the stack or the stack is empty when a closing bracket is encountered, the position of the error is returned. Otherwise, "Success" is returned if all brackets are properly balanced.

Uploaded by

Bhubaneswar Roy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

1: #include <iostream>

2: #include <stack>
3: #include <string>
4: #include <iostream>
5: #include <fstream>
6: #include <sstream>
7:
8: struct Bracket {
9: Bracket(char type, int position):
10: type(type),
11: position(position)
12: {}
13:
14: bool Matchc(char c) {
15: if (type == '[' && c == ']')
16: return true;
17: if (type == '{' && c == '}')
18: return true;
19: if (type == '(' && c == ')')
20: return true;
21: return false;
22: }
23:
24: char type;
25: int position;
26: };
27:
28: int main() {
29: std::string text;
30: getline(std::cin, text);
31:
32: int error_pos = 0;
33:
34: std::stack <Bracket> opening_brackets_stack;
35: for (int position = 0; position < text.length(); ++position) {
36: char next = text[position];
37:
38: if (next == '(' || next == '[' || next == '{') {
39: // Process opening bracket, write your code here
40: Bracket b(next, position+1);
41: opening_brackets_stack.push(b);
42: }
43:
44: if (next == ')' || next == ']' || next == '}') {
45: // Process closing bracket, write your code here
46: if(opening_brackets_stack.empty()) {
47: error_pos = position + 1;
48: break;
49: }
50: Bracket top = opening_brackets_stack.top();
51: opening_brackets_stack.pop();
52: if(!top.Matchc(next)) {
53: error_pos = position + 1;
54: break;
55: }
56: }
57: }
58:
59: // Printing answer, write your code here
60: if(error_pos==0 && opening_brackets_stack.empty())
61: std::cout << "Success";
62: else {
63: if(error_pos == 0) {
64: while(opening_brackets_stack.size()>1)
65: opening_brackets_stack.pop();
66: error_pos = opening_brackets_stack.top().position;
67: }
68: std::cout << error_pos;
69: }
70:
71: return 0;
72: }

You might also like