50 lines
1.3 KiB
C
50 lines
1.3 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
int match(char open, char close) {
|
|
return (open == '{' && close == '}') || (open == '[' && close == ']') ||
|
|
(open == '(' && close == ')') || (open == '<' && close == '>');
|
|
}
|
|
|
|
void check_brackets(const char *code) {
|
|
char stack[100];
|
|
int top = -1;
|
|
|
|
printf("Read: %s\n", code);
|
|
|
|
for (int i = 0; code[i] != '\0'; i++) {
|
|
char c = code[i];
|
|
if (c == '{' || c == '[' || c == '(' || c == '<') {
|
|
stack[++top] = c;
|
|
} else if (c == '}' || c == ']' || c == ')' || c == '>') {
|
|
if (top == -1) {
|
|
printf("Unexpected closing bracket %c in %d\n", c, i);
|
|
return;
|
|
}
|
|
if (!match(stack[top], c)) {
|
|
printf("Crossed bracket %c in %d, expected %c\n", c, i, stack[top]);
|
|
return;
|
|
}
|
|
top--;
|
|
}
|
|
}
|
|
if (top == -1) {
|
|
printf("All brackets OK\n");
|
|
} else {
|
|
printf("Missing closing brackets: %c\n", stack[top -1]);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
char code[100];
|
|
if (fgets(code, sizeof(code), stdin) != NULL) {
|
|
|
|
size_t len = strlen(code);
|
|
if (len > 0 && code[len - 1] == '\n') {
|
|
code[len - 1] = '\0';
|
|
}
|
|
check_brackets(code);
|
|
}
|
|
return 0;
|
|
}
|